Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Inheritance: One Subclass gets the Prototype, the other doesn't

I have a SuperClass "class", and this class is to be inherited (via the prototype chain) by SubClassA and SubClassB. However, while the inheritance appears to work for SubClassA, it fails for SubClassB. The code is 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 x to an object of SubClassA, and this should in turn give me a children property containing 9 SubClassB objects. It does this properly, but in turn, each SubClassB object should contain 9 SubClassC objects. However, after inspecting the console, I found that none of the SubClassB objects actually contain the childCell or the children properties that it was supposed to inherit via prototype.

In other words, x.children[0] returned SubClassB {num: 2}, and had none of the other properties.

Why does the inheritance work for SubClassA but not SubClassB?

like image 876
Shrey Gupta Avatar asked Mar 23 '26 03:03

Shrey Gupta


1 Answers

try reorder your declaration sample like

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

your problem - you call ChildB constructor before you add prototype to it

UPDATE

@Bagavatu when you create object you use prototype which set for constructor function, then you can change prototype properties and this changes will be apply to all objects with this prototype.
In your case you change reference to prototype so it does not apply to object which was created before. You can test it in simple example

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} 
like image 100
Grundy Avatar answered Mar 24 '26 16:03

Grundy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!