我想创建从超类 A 继承的子类 B。我的代码在这里:
function A(){
this.x = 1;
}
B.prototype = new A;
function B(){
A.call(this);
this.y = 2;
}
b = new B;
Console.log(b.x + " " + b.y );
运行时,显示 B 未定义。
我想创建从超类 A 继承的子类 B。我的代码在这里:
function A(){
this.x = 1;
}
B.prototype = new A;
function B(){
A.call(this);
this.y = 2;
}
b = new B;
Console.log(b.x + " " + b.y );
运行时,显示 B 未定义。
在尝试访问其原型之前,您必须定义 B 构造函数:
function A(){
this.x = 1;
}
function B(){
A.call(this);
this.y = 2;
}
B.prototype = new A;
b = new B;
console.log(b.x + " " + b.y ); // outputs "1 2"
B.prototype = new A;
function B(){
A.call(this);
this.y = 2;
}
应该
function B(){
A.call(this);
this.y = 2;
}
B.prototype = new A;
Lynda.com 建议您接下来将构造函数重新分配给 B,如下所示。
function B() {
A.call(this);
this.y = 2;
}
B.prototype = new A;
B.prototype.constructor = B;
在标准类派生中,从新创建的基类实例(B.prototype = new A)派生几乎普遍存在错误。基类构造函数至少会执行不必要的代码,最坏的情况可能会在没有输入参数的情况下崩溃,而输入参数不应该仅仅为了派生而人为创建。此外,基类实例的实例函数成为派生类原型的一部分,这完全是幸运的。
让我们清楚!如果您从基类构造函数(B.prototype = new A)创建的基类实例继承,您实际上并没有直接从基类继承!!你在继承链中创建了一个中介,即基类实例!!!哎哟!!!!这是低效的,因为在继承链中寻找继承的属性值有额外的深度。每次您犯此错误时,此深度都会累积。
那么正确的方法是什么。而不是 B.prototype = new A 你应该写 B.prototype = Object.create(A.prototype)。这可能在 09 中没有。但是在 09 中仍然有
protoProxy = function(myClass)
{
function foo(){};
foo.prototype = myClass.prototype;
return new foo();
}
作为 Object.create 的替代品。而不是 B.prototype = new A 你应该写 B.prototype = protoProxy(A) 在 09;