tvolodimir
3/6/2013 - 9:17 PM

faster bind by http://jsperf.com/bind-vs-emulate/9

/*
faster bind by http://jsperf.com/bind-vs-emulate/9
*/

(function () {
    var slice = Array.prototype.slice;
    Function.prototype.bind2 = function (context) {
        var f = this;
        var curriedArgs = slice.call(arguments, 1);
        if (curriedArgs.length) {
            return function () {
                var allArgs = curriedArgs.slice(0);
                for (var i = 0, n = arguments.length; i < n; ++i) {
                    allArgs.push(arguments[i]);
                }
                f.apply(context, allArgs);
            };
        } else {
            return createProxy(f, context);
        }
    };

    function createProxy(f, context) {
        return function bound() {
            if (!(this instanceof bound)) {
                f.apply(context, arguments);
            }
        }
    }
})();