1

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;

}
Winston Zhao
  • 79
  • 1
  • 8
  • There are still tutorials around that don't use `Object.create`? – Bergi Dec 16 '17 at 11:04
  • https://stackoverflow.com/questions/39911926/why-is-new-parent-often-used-to-initialize-prototypes-of-children-instead-of-o – Bergi Dec 16 '17 at 11:10
  • @Bergi I read the article that you linked explaining why the second one is bad, but I don't quite understand this statement: "Isn't it undesired to give different status to inherited properties vs own properties?" – – Winston Zhao Dec 16 '17 at 11:45

1 Answers1

1

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.

Sandip Ghosh
  • 719
  • 7
  • 13
  • I read @Bergi 's article that he linked explaining why the second one is bad, but I don't quite understand this statement: "Isn't it undesired to give different status to inherited properties vs own properties?" – Winston Zhao Dec 16 '17 at 11:45
  • 1
    In my fiddle from the second option, you can probably see that you are getting all the prototype properties(referred as inherited), as well as own properties of Vehicle into the prototype properties of Car. Here you can't distinguish between those two. That is the concern of that statement.. – Sandip Ghosh Dec 16 '17 at 11:55