andy-h
2/5/2014 - 7:56 PM

Cross-browser workaround for function binding

Cross-browser workaround for function binding

//creates a new function that, when called, has its `this` keyword set to the provided object, with a given sequence of arguments
// preceding any provided when the new function is called
//note: this is only a partial implementation; it may not work as expected in some scenarios.
// For instance, the resulting function cannot be used as a contructor.

if(!Function.prototype.bind){
	Function.prototype.bind = function bind(toObject){
		"use strict";
		var originalFn, boundArgs;
		
		if(typeof this !== "function") throw new TypeError("Owner object must be a Function");
		if(typeof toObject === "undefined" || toObject === null) throw new TypeError("toObject must be an object");
		
		originalFn = this;
		boundArgs = Array.prototype.slice.call(arguments, 1);
		
		return function (){
			var additionalArgs = Array.prototype.slice.call(arguments, 0);
			return originalFn.apply(toObject, boundArgs.concat(additionalArgs));
		};
	};
}