Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'd suggest the following pattern which makes use of a <a href="https://bitbucket.org/cggaertner/js-hacks/src/master/clone.js" rel="nofollow noreferrer"><code>clone</code> function</a> to inherit from the protoypes and not instances:</p> <pre><code>function Shape(x, y) { this.x = x; this.y = y; } Shape.prototype.draw = function() { throw new Error('Arbitrary shapes cannot be drawn'); }; function Square(x,y,side) { Shape.call(this, x, y); // call super constructor this.side = side; } // inherit from `Shape.prototype` and *not* an actual instance: Square.prototype = clone(Shape.prototype); // override `draw()` method Square.prototype.draw = function() { gotoXY(this.x,this.y); lineTo(this.x+this.side, this.y); // ... }; </code></pre> <p>It's important that methods reside in the prototype (which is as it should be anyway for performance reasons) so you can call the methods of a super class via</p> <pre><code>SuperClass.prototype.aMethod.call(this, arg1, arg2); </code></pre> <p>With some <a href="https://bitbucket.org/cggaertner/js-hacks/src/master/class5.js" rel="nofollow noreferrer">syntactic sugar</a>, you can make JS look like a classical class-based language:</p> <pre><code>var Shape = Class.extend({ constructor : function(x, y) { this.x = x; this.y = y; }, draw : function() { throw new Error('Arbitrary shapes cannot be drawn'); } }); var Square = Shape.extend({ constructor : function(x, y, side) { Shape.call(this, x, y); this.side = side }, draw : function() { gotoXY(this.x,this.y); lineTo(this.x+this.side, this.y); // ... } }); </code></pre>
 

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