Javascript 调用和应用函数仅在第一个参数上调用? [英] Javascript call and apply functions only called on first argument?

查看:30
本文介绍了Javascript 调用和应用函数仅在第一个参数上调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是由于我的误解而提出的.谨慎行事,因为阅读它可能会浪费您的时间.

我认为 callapply 会执行给定一组参数的函数,但我得到的测试结果令人困惑.查看我的测试代码:

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?

(在 Chrome 和 Firefox 中使用 Firebug 进行测试.)

(Tested in Chrome and Firefox with Firebug.)

推荐答案

Both 调用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 调用和应用函数仅在第一个参数上调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆