Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You want this instead:</p> <pre><code>function Man(name) { Human.call(this, name, "Male"); } </code></pre> <p><strong>What that code does</strong></p> <p>It seems like you're only trying to call the constructor of the parent, <code>Human</code>, which isn't the same is prototypal inheritance. The code above takes the constructor for <code>Human</code> and applies it to <code>this</code> - a new <code>Man</code> object.</p> <p><strong>What your code does</strong></p> <p>The line <code>Man.prototype = new Human(name, "Male")</code> is changing the prototype of <code>Man</code> <strong><em>every time a new Man is created</em></strong>. Not only that, you're completing re-assigning the prototype object, and so it will only apply to objects created <strong><em>after</em></strong> that assignment - i.e. not the first one. Hence, <code>m.name</code> is undefined.</p> <p><strong>Proper prototypal inheritance</strong></p> <p>Note that calling the parent's constructor, as in my code above, <em>won't</em> cause <code>Man</code> to automatically inherit any methods assigned to <code>Human.prototype</code>. The best way to do this is to clone <code>Human.prototype</code> into <code>Man.prototype</code> but outside of any constructors. Like this:</p> <pre><code>function Man(name) { Human.call(this, name, "Male"); } function inherit(parent, child) { if (Object.create) child.prototype = Object.create(parent.prototype); else { for (var key in parent.prototype) { if (!parent.prototype.hasOwnProperty(key)) continue; child.prototype[key] = parent.prototype[key]; } } } inherit(Human, Man); </code></pre> <p>This may seem rather verbose, and the alternative may be to do this:</p> <pre><code>Man.prototype = new Human('no name', 'Male'); </code></pre> <p>Which <em>will work</em>, but causes unwanted side-effects since we're forced to assign a dud name to the <code>prototype</code>, and it's letting the constructor for <code>Human</code> call an extra time just for assigning the prototype. Be warned if you go down this path and later change the <code>Human</code> constructor to do more than just assign properties to <code>this</code>.</p>
    singulars
    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.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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