I am new to the JavaScript world and I came up with this strange problem when I tried to inherit a prototype chain.
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);
First, I wanted to pass a parameter to the constructor of the parent classes, for example, the way they do, by calling super (args) in other OO languages. therefore this.constructor(param_1); Suitable enough for the purpose.
However, the output appears as
value in parent class 0 Constructor parameter : 666
It follows that the grandChild class skipped the prototype chain and, instead of calling the getObjWithParam () class, child () called getObjWithParam () on the parent class.
Does anyone know what's wrong here?
Note: There are 2 more conclusions that I want to add, and the second one is important. → If I try to find the constructor of the grandChild class on
console.log(gc.constructor)
conclusion i get
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); }; }
This is not quite what I expected. I expected to see a child class.
→ If I try to comment //this.constructor(param_1); in the class child () and grandChild (), the code will work exactly as expected.
Can someone explain this phenomenon, please.
It would also be greatly appreciated if anyone could suggest a workaround.
thanks