Search code examples
javascriptinheritanceprototypal-inheritance

Why do we use a temporary box in prototype inheritance?


The function below is one that Derek Banas on youtube on his OO Javascript tutorial uses.

function extend(Child, Parent){
  var Temp = function(){};

  Temp.prototype = Parent.prototype;

  Child.prototype = new Temp();

  Child.prototype.constructor = Child;

}

Why must we use the Temp prototype? Why can't we just do this:

function extend(Child, Parent){


  Child.prototype = new Parent();

  Child.prototype.constructor = Child;

}

Solution

  • Well. The main difference in both the function are in the lines

    Temp.prototype = Parent.prototype;
    

    and Child.prototype = new Parent();

    The first extend function shows prototypal inheritance solely. The Child wouldn't inherit any property from the Parent, which isn't there in its' prototype, as you can see, you are not calling the parent's constructor anywhere.

    I have created a fiddle to explain this here.

    In the second extend function, as you are calling the Parent's constructor Child.prototype = new Parent(), all the properties of the Parent, which are there in Parent's prototype alongwith all those which aren't will be inherited by the Child; i.e it will all go into the Child's prototype.

    I have created a fiddle here to explain this as well.