Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This kind of prototype inheritance is often done this way:</p> <pre><code>function Parent() {} function Child() { Parent.call(this); // call the constructor of the parent } var Constr = function() {}; Constr.prototype = Parent.prototype; Child.prototype = new Constr(); Child.prototype.constructor = Child; </code></pre> <p>So the "trick" is to assign the <code>Parent.prototype</code> as prototype to an empty function and set a new instance of this function as prototype of <code>Child</code>.</p> <p>This is done so that extending <code>Child.prototype</code> does not extend <code>Parent.prototype</code>.</p> <p>You also have to call the parent's constructor in the child's constructor. I guess this is the part you struggled with. Every function has a <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call"><code>call</code> <em><sup>[docs]</sup></em></a> and <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply"><code>apply</code> <em><sup>[docs]</sup></em></a> method which let's you explicitly set the element <code>this</code> should refer to inside the function.</p> <p>In your example, it would look like:</p> <pre><code>function Employee(name,title){ this.title=title; Person.call(this, name); } </code></pre> <p>without assigning the constructor to a property of the instance.</p> <p>In your example, <code>this.base(name)</code> works, because through assigning the constructor to a property of the instance (and calling it this way), <code>this</code> inside the function refers to that instance.</p> <hr> <p>There are several libraries implementing this pattern, e.g. <a href="http://closure-library.googlecode.com/svn/docs/closure_goog_base.js.html">Google Closure library</a>:</p> <pre><code>goog.inherits = function(childCtor, parentCtor) { /** @constructor */ function tempCtor() {}; tempCtor.prototype = parentCtor.prototype; childCtor.superClass_ = parentCtor.prototype; childCtor.prototype = new tempCtor(); childCtor.prototype.constructor = childCtor; }; </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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