Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There's usually two steps to mimic classical inheritance in javascript:</p> <ol> <li><p>Your subclass constructor needs to call the parent constructor</p></li> <li><p>Your subclass prototype needs to chain into the parent prototype</p></li> </ol> <p>the first step usually looks like</p> <pre><code>function Subclass(blah) { ParentClass.apply(this, arguments); } </code></pre> <p>The second step is trickier. On JS environments that implement the <code>__proto__</code> property, you could do</p> <pre><code>Subclass.prototype = { __proto__ : ParentClass.prototype, subclassMethod1: function() { /* ... */ } } </code></pre> <p>Unless you know exactly where your script will run (like in a node.js environment), you can't rely on <code>__proto__</code> being available to your script, so the general approach will require to use <a href="http://javascript.crockford.com/prototypal.html" rel="nofollow">Crockford's object() method</a>:</p> <pre><code>if (typeof Object.create !== 'function') { Object.create = function (o) { function F() {} F.prototype = o; return new F(); }; } Subclass.prototype = Object.create(ParentClass.prototype); Subclass.prototype.subclassMethod1 = function() { /* ... */ } </code></pre> <p>That's the gist of it. ES5 runtimes may have <code>Object.create()</code> already built-in, and that's fine.</p> <p>There are leftover things to complete the illusion of classic inheritance, such as the ability to easily call a parent class' overriden method. With what we have now, you'd need to have something like <code>ParentClass.prototype.overridenMethod.call(this, arg1, arg2)</code> in your Subclass method. Some OO libraries will helpfully define extra cruft on each of your subclass instances so you can use things like <code>this.superclass.overridenMethod(arg1, arg2)</code>.</p> <p>The implementation of that cruft is left as an exercise to the reader ;)</p>
 

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