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?
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With