问题
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.)
回答1:
Both call and apply only 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).
function foo(a, b, c) {
};
foo.call(this, 1, 2, 3); // a == 1, b == 2, c == 3;
foo.apply(this, [1,2,3]); // a == 1, b == 2, c == 3;
If you want to call the function multiple times, you can accomplish this by simply putting the call in a loop.
回答2:
This is expected, the arguments you pass will be present in your increment function (as arguments see here for reference), but you are only calling the function once.
回答3:
It seems that you are under the impression that the call and apply methods should call the functon once for each parameter. That is not the case, it only calls the function once.
The apply methods takes an array of arguments:
func.apply(this, [1, 2, 3]);
The call methods takes an argument list:
func.call(this, 1, 2, 3);
来源:https://stackoverflow.com/questions/8605788/javascript-call-and-apply-functions-only-called-on-first-argument