问题描述
由于我的误会,提出了此问题.请谨慎处理,因为阅读可能会浪费您的时间.
我认为call
和apply
会在给定一组参数的情况下执行一个函数,但我的测试结果令人困惑.查看我的测试代码:
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)
我希望z
在执行后为3.但是,z为1.
I would expect z
to be 3 after execution. However, z is 1.
(function(){++(window.z)}).apply(this, [1, 2, 3])
这里也一样. z == 1;
我也尝试简单地记录输入参数:
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);
结果?仅记录了1个.
我在这里做什么错了?
Result? Only 1 is logged.
What am I doing wrong here?
(在具有Firebug的Chrome和Firefox中进行了测试.)
(Tested in Chrome and Firefox with Firebug.)
推荐答案
两者 call
和 apply
一次调用该函数.区别在于调用参数的传递方式.
Both call
and apply
only call the function once. The difference is how the arguments to the invocation are passed.
通过调用,上下文之后的每个参数(第一个参数)都是一个参数.使用apply时,第二个参数应为参数的 like 数组对象(第一个参数仍提供上下文).
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.
这篇关于Javascript调用和应用函数仅在第一个参数上调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!