I'll try to explain it from what I understand. The syntax for using apply is:
fun.apply(thisArg, [argsArray])
Here, thisArg states the context which will be applied to function. (Eg, this). [argsArray] is the array of arguments to the function.
When you do this:
addToThis.apply(obj,arr)
you're basically passing arr=[1,2,3]
as the arguments to your addToThis function. Thus, a
becomes 1, b
becomes 2, if you had a c
in your function definition, that would be 3..and so on till it reaches the length of your array.
See this fiddle, here console.log(c)
prints out the third element in your array. But, if you wrote this code:
var obj = {num:2};
var addToThis = function(a,b,c,d){
console.log(a); //prints first element in array
console.log(b); //prints second element
console.log(c); //prints third element
console.log(d); //prints undefined because there is no forth element
};
var arr = [1,2,3];
addToThis.apply(obj,arr);
Hope this helps.
apply
sends the contents of the array as individual arguments - soa
will be set to1
, andb
set to2
. What are you expecting to happen? – Shadow