0
votes

When I call the function addToThis and pass in the obj the console.log(a) outputs the first array index value which is 1 instead of the obj why?

var obj = {num:2};

var addToThis = function(a,b){
  console.log(a);
  return this.num + a + b;
};

var arr = [1,2,3];
console.log(addToThis.apply(obj,arr));
2
apply sends the contents of the array as individual arguments - so a will be set to 1, and b set to 2. What are you expecting to happen?Shadow

2 Answers

0
votes

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

When you use apply(), the first argument is the this argument, and the second argument is an array of arguments to be passed to the function. In your case, a is mapped to 1 and b is mapped to 2. If you were to add a third argument, c, it would be mapped to 3.

More simply put, the first argument in apply() is just what this will refer to in your function. The second argument is an array of arguments that get passed to the function.

If you were to add console.log(this) you would see your object.

var obj = {num:2};

var addToThis = function(a,b){
  console.log(a);
  console.log(this);
  return this.num + a + b;
};

var arr = [1,2,3];
console.log(addToThis.apply(obj,arr));
0
votes

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.