【发布时间】:2013-03-11 12:05:57
【问题描述】:
我希望稍微简化 Javascript 中的继承。从目前收集到的资料来看,实现“类”之间“继承”的好方法如下:
function ParentClass() {
//Parent Constructor
}
ChildClass.prototype = new ParentClass(); //Step 1: Use parent as prototype
ChildClass.prototype.constructor = ChildClass; //Step 2: Designate appropriate constructor
function ChildClass() {
ParentClass.call(this, arguments); //Step 3: Call the parent's constructor from the child's
//Child Constructor
}
我喜欢将流程分为三个“步骤”,如我在上面标记的(步骤 1、2 和 3)。我想将所有这三个步骤放在一个函数中(来自 Java 背景,我将其标记为“扩展”),我可以从函数构造函数对象中调用它,如下所示:
function ParentClass() {
//Parent Constructor
}
ChildClass.extend(ParentClass); //Execute steps 1, 2 and 3 all in this function
function ChildClass() {
//Child Constructor
}
这是我目前所拥有的:
Function.prototype.extend = function (parent) {
var oldConstructor = this.prototype.constructor;
this.prototype = new parent(); //Step 1
this.prototype.constructor = function (arguments) { //Step 2
parent.apply(this, arguments); //Step 3
oldConstructor(arguments);
};
}
extend 函数的第 1 步和第 2 步在这种情况下工作正常,但第 3 步给我带来了问题。我试图做的是用一个调用父构造函数的新函数替换子构造函数,然后是子构造函数。但是,当我运行它时,不会调用父构造函数。我无法确定问题(我是否正确使用了“this”关键字?);也许我以错误的方式接近这个。可以创建一个功能来做到这一点,对吧?如何制作有效的“扩展”功能?
更新:
真正的问题似乎在于我对“this”关键字的使用。这是我现在正在查看的代码:
function ParentClass(x) {
this.value = x;
}
function ChildClass() {
}
ChildClass.extend(ParentClass);
function testtest() {
var a = new ParentClass("hello world"); //Alerts "hello world"
alert(a.value);
var b = new ChildClass("hello world"); //Alerts "undefined"
alert(b.value);
}
为什么第一个警报有效而第二个无效?我认为“this”是指函数运行的上下文,在这两种情况下都是调用构造函数(a或b)的对象。
【问题讨论】:
-
我刚刚尝试了您的扩展功能,并且正在调用父构造函数。你能举一个不适合你的例子吗?
-
问题似乎出在“this”关键字上。在我的父构造函数(this.x = y)中设置属性,但这些属性不适用于子对象实例。正在调用所有函数,但未按预期设置属性。
标签: javascript inheritance this