admin管理员组文章数量:1316012
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.)
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.)
Share Improve this question edited Dec 22, 2011 at 15:24 Protector one asked Dec 22, 2011 at 15:09 Protector oneProtector one 7,3315 gold badges67 silver badges88 bronze badges3 Answers
Reset to default 6Both 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 acplish this by simply putting the call in a loop.
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);
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.
本文标签: Javascript call and apply functions only called on first argumentStack Overflow
版权声明:本文标题:Javascript call and apply functions only called on first argument? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741961166a2407288.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论