0

I'm trying to learn JS OOP, and there is this tutorial where we are given this code:

function extend(Child, Parent) {
    var Temp = function() {};
    Temp.prototype = Parent.prototype;
    Child.prototype = new Temp();
    Child.prototype.constructor = Child;
}

I want to know, why can't you just say:

function extend(Child, Parent) {
   Child.prototype = Parent.prototype;
   Child.prototype.constructor = Child;
}

And avoid the hassle of making an intermediary, sorry if this is obvious, I'm a beginner.

  • 2
    That intermediary is a horrible ES3 thing (i.e. outdated for a long time). You should just do `Child.prototype = Object.create(Parent.prototype)` instead of using a `Temp` constructor. – Bergi Jun 16 '16 at 21:10
  • 2
    Your second block of code won't work because `Child.prototype` and `Parent.prototype` will be pointing at exactly the same object. Any changes you make to `Child.prototype` will affect `Parent.prototype` also. You need to use `Object.create(Parent.prototype)` to make a proper copy of the prototype. Your first block of code is outdated and not the current way of doing things. – jfriend00 Jun 16 '16 at 21:11
  • Good to work to understand the prototypal inheritance, kind of key to JavaScript – Mark Schultheiss Jun 16 '16 at 21:46

0 Answers0