Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat will be a good minimalistic Javascript inheritance method?
    text
    copied!<p>I'm rewriting a JavaScript project, and I want to be able to use object oriented methodologies to organize the mess that the current code is. The main concern is that this JavaScript is supposed to run as a widget inside 3rd party websites and I can't have it conflicting with other JavaScript libraries that other websites may use.</p> <p>So I'm looking for a way to write "class-like" inheritance in JavaScript that has the following requirements:</p> <ol> <li>No external libraries or things that would conflict with an external library (that precludes copy&amp;paste from an external library).</li> <li>Minimalistic - I don't want the support code to be larger then a few lines of code and I don't want the developers to need a lot of boiler-plate every time they define a new class or methods.</li> <li>Should allow for dynamically extending parent objects so that child objects see the changes (prototype).</li> <li>Should allow for constructor chaining.</li> <li>Should allow for <code>super</code> type calls.</li> <li>Should still feel JavaScript-ish.</li> </ol> <p>Initially I tried to work with simple prototype chaining:</p> <pre><code>function Shape(x,y) { this.x = x; this.y = y; this.draw = function() { throw new Error("Arbitrary shapes cannot be drawn"); } } function Square(x,y,side) { this.x = x; this.y = y; this.side = side; this.draw = function() { gotoXY(this.x,this.y); lineTo(this.x+this.side, this.y); ... } } Square.prototype = new Shape(); </code></pre> <p>And that solves requirements 1, 2 and 6 but id does not allow super calls (new functions override parent functions), constructor chaining and dynamically extending a parent does not provide the new methods to a child class.</p> <p>Any suggestions will be welcome.</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