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.

  1. The word prototype does not appear in this code. So nothing is being inherited. You create a new child and then explicitly run the parent constructor function on that new child. The parent constructor function then add a method to to the new child.

    If you put getObjWithParam on parent.prototype.getObjWithParam instead then you will see that it will not carry over.

  2. 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 invoking parent.call(a, [...]) you invoke parent function and set scope to a. That means any modification made to this is also made to a (because it’s the same object).

  3. 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.