Old post but a newer approach ;)
Function.prototype.bind = function(){
var fn = this,
context = arguments[0],
args = Array.prototype.slice.call(arguments, 1);
return function(){
return fn.apply(context, args.concat([].slice.call(arguments)));
}
}
obj = {'abc':'x'};
var func = function() {
console.log(arguments);
alert(this.abc);
}
var x = func.bind(obj);
console.log(x(1,2,3));
This is a very good example to explain. Run it and check the console log.
Then modify the code to leave out
[].slice.call(arguments)
You will see that the console.log of the execution of x(1,2,3) is not showing up the arguments anymore. This is because the arguments objects is a local variable within all functions.
That might sound a bit confusing, but what it means is basically:
var x = func.bind(obj,1,2,3);
Returns this function internally:
function() {
return fn.apply(obj, [1,2,3].concat([].slice.call(arguments)));
}
So it is more of a template for the function.
When you do now run it like:
x(4,5,6)
This will be ran:
fn.apply(obj, [1,2,3].concat([].slice.call(arguments)))
with a special arguments object = {0:4,1:5,2:6} , which can be converted into an array using [].slice.call
where arguments is a local object, that is automatically beeing assigned during the invokation of the function.