Inheritance example

Sample code for implementing inheritance in JavaScript.

by Liam Talbot

HTML

<div id="results"></div>

JavaScript

// override extension method
Function.prototype.override = function(func)
{
    var superFunction = this;
    return function()
    {
        this.superFunction = superFunction;
        return func.apply(this,arguments);
    };
};

// classes
function A() {
    this.id = Math.random();     // instance property
}
function B() { A.call(this); }
function C() { B.call(this); }
function D() {
    C.call(this);
    this.ddd1 = function() { $('#results').append("<p>This method (ddd1) is declared in D!</p>"); }
    this.ddd2 = function() { $('#results').append("<p>This method (ddd2) is declared in D!</p>"); }
}
function E() {
    D.call(this);
    this.ddd2 = this.ddd2.override(function() {
        this.superFunction();
        $('#results').append("<p>This method (ddd2) was overridden and is declared in E!</p>");
    });
}


// set up the inheritance chain (order matters)
B.prototype = Object.create(A.prototype);
C.prototype = Object.create(B.prototype);
D.prototype = Object.create(C.prototype);
E.prototype = Object.create(D.prototype);

// add custom functions to each
E.prototype.foo = function() { $('#results').append("<p>E.prototype.foo called!</p>"); };
D.prototype.bar = function() { $('#results').append("<p>D.prototype.bar called!</p>"); };
C.prototype.baz = function() { $('#results').append("<p>C.prototype.baz called!</p>"); };
B.prototype.wee = function() { $('#results').append("<p>B.prototype.wee called!</p>"); };
A.prototype.woo = function() { $('#results').append("<p>A.prototype.woo called!</p>"); };

// some tests
e = new E();
e.foo();
e.bar();
e.baz();
e.wee();
e.woo();
$('#results').append("<br /><br />");
$('#results').append("<p>e.id = '" + e.id + "'</p>");
$('#results').append("<br /><br />");
e.ddd1();
e.ddd2();
$('#results').append("<br /><br />");
$('#results').append("<p>e instanceof E = '" + (e instanceof E) + "'</p>");
$('#results').append("<p>e instanceof D = '" + (e instanceof D) + "'</p>");
$('#results').append("<p>e instanceof C = '" + (e...