Javascript inheritance without child.prototype = new parent();-Collection of common programming errors
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
child
and then explicitly run theparent
constructor function on that newchild
. Theparent
constructor function then add a method to to the newchild
.If you put
getObjWithParam
onparent.prototype.getObjWithParam
instead then you will see that it will not carry over. -
You invoke parent constructor in child constructor. Because parent constructor sets
this.getObjWithParam = function[...]
it’ll also set it for child. Notice that this has nothing to do with prototype. By invokingparent.call(a, [...])
you invoke parent function and set scope toa
. That means any modification made tothis
is also made toa
(because it’s the same object). -
parent.call(this, [ param_1 ])
Assigns Parent.param_1 and Parent.getObjWithParam to childObj. This has nothing to do with inheritance. Consider this formulation:
var foo = {}; //class parent function parent(param_1) { this.param_1 = param_1; this.getObjWithParam = function(val) { console.log(this.param_1); console.log(val); }; }; //class child function child(param_1) { parent.call(foo, [ param_1 ]); }; var childObj = new child( 'lets give foo a param_1'); console.log( typeof childObj.getObjWithParam ); // Undefined foo.getObjWithParam(); // ["lets give foo a param_1"]
here you are passing foo as a scope to .call() thus the properties are assigned to foo.
Originally posted 2013-11-09 23:12:37.