JavaScript Inheritance Example

by chintsu

JavaScript

var A = (function () {
    var A = function () {};

    A.prototype.p1 = 2;
    A.prototype.f1 = function () {
        return 7;
    };

    return A;
})();

var B = (function (_super) {
    var B = function () {};

    inherits(B, _super);

    B.prototype.p2 = 'Hello';
    B.prototype.f2 = function (x) {
        return x * 2;
    };

    return B;
})(A);

var C = (function (_super) {
    var C = function () {
        this.p2 = 'Bye';
    };

    inherits(C, _super);

    return C;
})(B);

var D = (function (_super) {
    var D = function () {
        this.p4 = 7 * this.p1;
    };

    inherits(D, _super);

    D.prototype.f2 = function (x) {
        return D.superClass_.f2(x) * 5;
        // return _super.prototype.f2(x) * 5;
    };
    D.prototype.f4 = function (x) {
        return this.f1() + this.f2(x);
    };

    return D;
})(C);

var aObject = new A();
var bObject = new B();
var cObject = new C();
var dObject = new D();

console.log(aObject);
console.log(bObject);
console.log(cObject);
console.log(dObject);
console.log(dObject.f4(2));

console.log('---');

var Auto = (function () {
    var Auto = function () {};

    return Auto;
})();

var Cabriolet = (function (_super) {
    var Cabriolet = function () {};

    inherits(Cabriolet, _super);

    Cabriolet.prototype.hasRoof = false;

    return Cabriolet;
})(Auto);

console.log(new Auto());
console.log(new Cabriolet());

function inherits(Child, Parent) {
    // create empty proxy-function
    var F = function () {};

    // assign Parent.prototype to prototype of this empty proxy-function
    F.prototype = Parent.prototype;

    // create new object and assign it to the Child.prototy
    // Child.prototype is empty object
    Child.prototype = new F();

    // Child.prototype.constructor set to Child
    Child.prototype.constructor = Child;

    // each class should know about its parent
    Child.superClass_ = Parent.prototype;
}