Nathan Witt

Class Inheritance in JavaScript

December 29, 2012

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

// ========= Extended Primitives =========

Function.prototype.extends = function(o) {  
    var cn = this;  
    this.prototype = new o;  
    this.prototype.constructor = cn;  
};

// ========= Extended Primitives =========

Sample inheritance

/***************************************  
 * 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';