Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the correct prototype affectation in javascript inheritance?
    primarykey
    data
    text
    <p>I read several articles on js inheritance already (<a href="http://alexsexton.com/blog/2013/04/understanding-javascript-inheritance">this one</a>, <a href="http://ericleads.com/2013/02/fluent-javascript-three-different-kinds-of-prototypal-oo/">this one</a>, <a href="http://javascript.crockford.com/private.html">this one</a>, etc.)</p> <p>In <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Inheritance">this article</a> from Mozilla, "classic" inheritance is shown as this : (I uniformized examples)</p> <pre><code>// inherit Base function Derived() { ... } Derived.prototype = new Base(); &lt;------- Derived.prototype.constructor = Derived; &lt;------- </code></pre> <p>However in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create">this article</a> I see :</p> <pre><code>// inherit Base function Derived() { ... } Derived.prototype = Object.create(Base.prototype); &lt;------- Derived.prototype.constructor = Derived; </code></pre> <p>Moreover I have also seen this :</p> <pre><code>Derived.prototype = Base.prototype; </code></pre> <p>And I also experimented and couldn't find the use of <code>constructor</code> affectation :</p> <pre><code>Derived.prototype.constructor = Derived; &lt;--- it still work if I skip this line </code></pre> <p>if I skip this line, <code>new Derived()</code> correctly calls <code>Derived()</code> anyway.</p> <p>So 1) what is correct :</p> <ol> <li><code>Derived.prototype = new Base();</code></li> <li><code>Derived.prototype = Object.create(Base.prototype);</code></li> <li><code>Derived.prototype = Base.prototype;</code></li> <li>other ?</li> </ol> <p>And 2) is <code>Derived.prototype.constructor = Derived;</code> really needed ? Why ?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload