我想创建继承自超类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 );
Run Code Online (Sandbox Code Playgroud)
运行时,显示B未定义.
CMS*_*CMS 17
在尝试访问其原型之前,必须定义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"
Run Code Online (Sandbox Code Playgroud)
B.prototype = new A;
function B(){
A.call(this);
this.y = 2;
}
Run Code Online (Sandbox Code Playgroud)
应该
function B(){
A.call(this);
this.y = 2;
}
B.prototype = new A;
Run Code Online (Sandbox Code Playgroud)
小智 5
Lynda.com建议您接下来将构造函数重新分配给B,如下所示.
function B() {
A.call(this);
this.y = 2;
}
B.prototype = new A;
B.prototype.constructor = B;
Run Code Online (Sandbox Code Playgroud)