Pages

Saturday, September 20, 2014

With a new thought, revisited previous post: JavaScript Chained Inheritance
Included ability to inherit from either an Object or a Constructor function

New Idea


hillHigh.inherit = function (subClass) {
    return new function () {
        var superClasses = [subClass],
            result,
            convertToContructorFunctions = function () {
                for (var i = 0, length = superClasses.length; i < length; i++) {
                    if (Object.prototype.toString.call(superClasses[i]) === "[object Object]") {
                        console.log(i);
                        superClasses[i] = superClasses[i].constructor;
                    }
                }
            };

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

        this.provide = function () {
            convertToContructorFunctions();

            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 superClasses[0];
        };

        return this;
    };
};


Results



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

//All Constructor functions
var result0 = hillHigh.inherit(fn3).from(fn2).from(fn1).provide();
//All Objects
var result1 = hillHigh.inherit(Fn3).from(Fn2).from(Fn1).provide();
//Mix Objects and constructor functions
var result2 = hillHigh.inherit(fn3).from(Fn2).from(fn1).provide();

console.log("result0: " + result0.a);
console.log("result0: " + result0.b);
console.log("result0: " + result0.c);

console.log("result1: " + result1.a);
console.log("result1: " + result1.b);
console.log("result1: " + result1.c);

console.log("result2: " + result2.a);
console.log("result2: " + result2.b);
console.log("result2: " + result2.c);


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