As is the case with most design patterns, the JS world is hardly united. Still, there are practical applications for OOP in JavaScript. This method is the result of a few days of trial and error with multiple approaches. Unlike regular prototypal inheritance, class properties are per-instance so changing one ExtendedClass instance property will not affect any other instances.
The example below illustrates a minimal implementation, but the pattern can be evolved to support multiple inheritance and singletons too. My function sugar—extends—is marked reserved for future use by ECMAScript5 so you if you run strict mode, just get rid of the trailing ‘s’ to prevent conflict.
Function sugar
1 2 3 4 5 6 7 8 9 | // ========= Extended Primitives ========= Function.prototype.extends = function(o) { var cn = this; this.prototype = new o; this.prototype.constructor = cn; }; // ========= Extended Primitives ========= |
Sample inheritance
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | /*************************************** * ParentClass * @type Class */ function ParentClass() { } ParentClass.prototype.myProp = "Parent Property"; /*************************************** * ExtendedClass * @type Class */ function ExtendedClass() { // extended properties will be static unless next line is uncommented ParentClass.call(this); } // Inheritance ExtendedClass.extends(ParentClass); // Public Properties ExtendedClass.prototype.myExtendedProp = 'Extended Property'; |