Pages

Saturday, June 7, 2014

Chained JavaScript Inheritance.

Chained JavaScript Inheritance. Thought this may be useful.

Define Objects:

var Fn1 = function () {
    this.a = "a";
};
var Fn2 = function () {
    this.b = "b";
}
var Fn3 = function () {
    this.c = "c";
}

Inheritance

inherit(Fn3).from(Fn2).from(Fn1).provide();

Extend

Fn1.prototype.aa = function () {
    return "AA";
};
Fn2.prototype.bb = function () {
    return "BB";
};
Fn3.prototype.cc = function () {
    return "CC";
};

Instantiate

var ff = new Fn3();

Inherit Object

var inherit = function (subClass) {
    return new function () {
        var superClasses = [subClass],
            result;

        this.from = function (superClass) {
            superClasses.push(superClass);
            return this;
        };

        this.provide = function () {
            for (var i = superClasses.length - 1; i > 0; i -= 1) {
                superClasses[i-1].prototype = new superClasses[i]();
                superClasses[i-1].prototype.constructor = superClasses[i-1];
            }
            return subClass;
        };

        return this;
    };
};

This post is for the purpose of my notes only and sometimes a rant.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford

No comments:

Post a Comment