Javascript继承:一个子类获取Prototype,另一个不获取

Shr*_*pta 4 javascript oop inheritance prototype

我有一个SuperClass"类",这个类是通过SubClassA和继承(通过原型链)SubClassB.但是,虽然继承似乎有效SubClassA,但它失败了SubClassB.代码如下:

function SuperClass(childCell){
    this.childCell = childCell;
    this.children = new Array(9);
    for(i=0; i<9; i++) {
        this.children[i] = new this.childCell();
    }
}
function SubClassA(){
    this.num = 1;
}
SubClassA.prototype = new SuperClass(SubClassB);
function SubClassB(){
    this.num = 2;
}
SubClassB.prototype = new SuperClass(SubClassC);
function SubClassC(){
    this.num = 3;
}
var x = new SubClassA();
Run Code Online (Sandbox Code Playgroud)

在这段代码中,我设置x了一个对象SubClassA,这应该反过来给我一个children包含9个SubClassB对象的属性.它正确地执行此操作,但反过来,每个SubClassB对象应包含9个SubClassC对象.然而,检查控制台后,我发现,没有任何的SubClassB对象实际上包含了childCell或者children它的属性应该通过原型继承.

换句话说,x.children[0]返回SubClassB {num: 2},并没有其他属性.

为什么继承有效SubClassA但不是SubClassB

Gru*_*ndy 7

尝试重新排序您的声明样本

function Parent(childCell){
    this.childCell = childCell;
    this.children = new Array(9);
    for(var i=0; i<9; i++) {
        this.children[i] = new this.childCell();
    }
}
function ChildA(){
    this.num = 1;
}
function ChildB(){
    this.num = 2;
}
function ChildC(){
    this.num = 3;
}

ChildB.prototype = new Parent(ChildC);
ChildA.prototype = new Parent(ChildB);
Run Code Online (Sandbox Code Playgroud)

你的问题 - ChildB在向它添加原型之前调用构造函数

UPDATE

@Bagavatu在创建对象时使用原型设置构造函数,然后可以更改原型属性,此更改将应用​​于具有此原型的所有对象.
在您的情况下,您更改对原型的引用,因此它不适用于之前创建的对象.你可以用简单的例子来测试它

function A() {this.cell = 10}
function B() {this.num =1}

var b1 = new B(); // b1 = {num:1}

B.prototype = new A();
var b2 = new B(); // b1 = {num:1}, b2 = {num:1, cell:10} 
Run Code Online (Sandbox Code Playgroud)