Edit: this question was asked due to my misunderstanding. Proceed with caution, as reading it might waste your time.
I thought call and apply would execute a function given a set of arguments, but I’m getting confusing test results. See my test code:
window.z = 0;
(function(){++(window.z)}).call(this, 1, 2, 3)
I would expect z to be 3 after execution. However, z is 1.
(function(){++(window.z)}).apply(this, [1, 2, 3])
Same here. z == 1;
I tried simply logging the input argument as well:
var x = function(y){console.log(y);}
x.call(this, 1, 2, 3);
Result? Only 1 is logged.
What am I doing wrong here?
(Tested in Chrome and Firefox with Firebug.)
Both
callandapplyonly call the function once. The difference is how the arguments to the invocation are passed.With call, each parameter after the context (first parameter), is a parameter. With apply, the second parameter should be an array like object of parameters (the first parameter still provides the context).
If you want to call the function multiple times, you can accomplish this by simply putting the call in a loop.