This is the code for _.bind, taken from the Underscore library. I don’t understand the business of taking the empty function, changing it’s prototype, etc.
var ctor = function(){};
_.bind = function bind(func, context) {
var bound, args;
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError;
args = slice.call(arguments, 2);
return bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
ctor.prototype = func.prototype;
var self = new ctor;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) return result;
return self;
};
};
It basically is there so that if you call
new bound(), you’re able to bind arguments for thenewcall. E.g.:I tried to explain the code a bit.