What is the correct prototype affectation in javascript inheritance?

Viewed 160

I read several articles on js inheritance already (this one, this one, this one, etc.)

In this article from Mozilla, "classic" inheritance is shown as this : (I uniformized examples)

// inherit Base
function Derived() { ... }
Derived.prototype = new Base();            <-------
Derived.prototype.constructor = Derived;   <-------

However in this article I see :

// inherit Base
function Derived() { ... }
Derived.prototype = Object.create(Base.prototype);    <-------
Derived.prototype.constructor = Derived;

Moreover I have also seen this :

Derived.prototype = Base.prototype;

And I also experimented and couldn't find the use of constructor affectation :

Derived.prototype.constructor = Derived; <--- it still work if I skip this line

if I skip this line, new Derived() correctly calls Derived() anyway.

So 1) what is correct :

  1. Derived.prototype = new Base();
  2. Derived.prototype = Object.create(Base.prototype);
  3. Derived.prototype = Base.prototype;
  4. other ?

And 2) is Derived.prototype.constructor = Derived; really needed ? Why ?

2 Answers
Related