Javascript inheritance: one subclass gets the prototype, the other doesn't.

I have a class, SuperClass"and this class must be inherited (via the prototype chain) on SubClassAand SubClassB. However, although inheritance works for SubClassA, it does not execute for SubClassB. The code below:

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();

In this code, I set xto an object SubClassA, and this should in turn give me a property childrencontaining 9 SubClassBobjects. He does it right, but, in turn, each object SubClassBmust contain 9 SubClassCobjects. However, after checking the console, I found that none of the objects SubClassBactually contained properties childCellor childrenthat it had to inherit through the prototype.

, x.children[0] SubClassB {num: 2} .

SubClassA, SubClassB?

+4
2

,

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);

- 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} 
+7

. javascript, .

function Superclass() { }
Superclass.prototype.someFunc = function() { };

function Subclass() { }
Subclass.prototype = new Superclass();
Subclass.prototype.anotherFunc = function() { };

var obj = new Subclass();
-1

All Articles