Compromise of Delegate and Prototype and Module

by Douglas Enas

JavaScript

function Delegate(Target, TargetMember) {
    //Create an array of extra parameters
    var PresetParams = new Array();
    for (var i = 2; i < arguments.length; i++)
    PresetParams[i - 2] = arguments[i];

    //Create our return value
    return function() {
        //Create an array of params
        var Params = new Array(arguments.length);
        for (var i = 0; i < arguments.length; i++)
        Params[i] = arguments[i];

        //Call it
        return TargetMember.apply(Target, PresetParams.concat(Params));
    }
}

var TestObj = (function() {
    // use strict here istead of at top of file.
    'use strict';
    // constructor
    var TestObj = function(value) {
        if (!(this instanceof TestObj)) return new TestObj();
        // public var
        this._value = value;
    };

    TestObj.prototype = function() {
        // these are private
        var _giveMe = function() {
            return this._value;
        };
        var _callMeLaterTestObj = function() {
            console.log('I am ' + this.constructor.name + ' my value is ' + this._value);
        };

        // public API
        return {
            GiveMe: _giveMe,
            CallMeLaterTestObj: _callMeLaterTestObj
        }

    }();
    return TestObj;
}).call(this);

function CallMeLater(v, i) {
    //setTimeout(function () { v.CallMeLaterTestObj() }, 10);
    // or
    setTimeout(Delegate(v, v.CallMeLaterTestObj), 10);
}



var V1 = new TestObj(1);
var V2 = new TestObj(2);
var V3 = new TestObj(3);


console.log('V1= ' + V1.GiveMe());
console.log('V2= ' + V2.GiveMe());
console.log('V3= ' + V3.GiveMe());
console.log('---');

V1.CallMeLaterTestObj();

console.log('---');

CallMeLater(V1, 1);
CallMeLater(V2, 2);
CallMeLater(V3, 3);