I was playing around with javascript prototype chain inheritance and i came accross this funny behaviour.
I have a parent class and a child class
//class parent
function parent(param_1) {
this.param_1 = param_1;
this.getObjWithParam = function(val) {
console.log(this);
console.log("Constructor value in parent class " + this.param_1);
console.log("tguha ----> parent, val " + val);
};
};
//class child
function child(param_1) {
parent.call(this, [ param_1 ]);
};
var childObj = new child(100);
childObj.getObjWithParam(200);
and i get the output as
**>child**
Constructor value in parent class 100
tguha ----> parent, val 200
and nowhere i’m doing //child.prototype = new parent();
and still the parent class is inherited.
Could anyone help me by explaining this scenario please.
The word prototype does not appear in this code. So nothing is being inherited. You create a new
childand then explicitly run theparentconstructor function on that newchild. Theparentconstructor function then add a method to to the newchild.If you put
getObjWithParamonparent.prototype.getObjWithParaminstead then you will see that it will not carry over.