I'm a newbie in the JavaScript world, and I came up with this weird problem when i was attempting prototype chaining inheritence.
I have 3 classes
//class parent
function parent(param_1){
this.param = param_1;
this.getObjWithParam = function(val){
console.log("value in parent class "+val);
console.log("Constructor parameter : "+this.param);
};
};
//class child
function child(param_1){
this.constructor(param_1);
this.getObjWithParam = function(val){
console.log("value in child class "+val);
val = Number(val)+1;
child.prototype.getObjWithParam.call(this, [val]);
};
};
child.prototype = new parent();
//class grandChild
function grandChild(param_1){
this.constructor(param_1);
};
grandChild.prototype = new child();
var gc = new grandChild(666);
gc.getObjWithParam(0);
Firstly, I wanted to pass a parameter to the constructor of the parent classes, like the way they do by calling super(args) in other OO languages.
so this.constructor(param_1); fairly suits the purpose.
However, the output comes up as
value in parent class 0
Constructor parameter : 666
Which suggests, that the class grandChild has skipped the prototype chain, and instead of calling getObjWithParam() of child() class, has called getObjWithParam() of the parent class.
Does anyone have any idea what goes wrong here?
NB: 2 more findings i want to add, and the second one is the important one. --> If I try to find the constructor of grandChild class by
console.log(gc.constructor)
the output i get is
function parent(param_1){
this.param = param_1;
this.getObjWithParam = function(val){
console.log("value in parent class "+val);
console.log("Constructor parameter : "+this.param);
};
}
which is the not quite the thing i expected. I was expecting to see the child class.
--> If I try to comment //this.constructor(param_1); in the child() and the grandChild() class, the code works exactly as expected.
Could anyone explain this phenomenon please.
Also, it'll be highly appreciated if anyone could suggest an workaround.
Thanks