Can someone please explain why when we use bind instead of apply this does not work correctly.
Lets say I have a simple function:
function addFourNumbers(a,b,c,d){
return a+b+c+d;
}
I try to create a function that I could use to call the above function later with the correct value of 'this' and parameters could be passed anytime:
function bind(fn, thisArg){
var outArg = [].slice.call(arguments, 2);
return function(){
var inArg = [].slice.call(arguments);
var allArg = outArg.concat(inArg);
return fn.apply(thisArg, allArg);
}
}
Now when I call the following it works:
var t = bind(addFourNumbers,this,1)
t(2,3,4); //output 10
var t = bind(addFourNumbers,this,1,2)
t(3,4); //output 10
Now I'm confused if I change apply to bind
function bind(fn, thisArg){
var outArg = [].slice.call(arguments, 2);
return function(){
var inArg = [].slice.call(arguments);
var allArg = outArg.concat(inArg);
return fn.bind(thisArg, allArg);
}
}
and try to execute:
var t = bind(addFourNumbers,this,1,2)
t(3,4)(); //output 1,2,3,4undefinedundefinedundefined
Any suggestions why?
Thanks