在javascript中传递函数和函数调用本身之间的区别是什么? [英] What's the differenct between passing a function and the function call itself in javascript?
问题描述
在我正在构建的应用程序中,我正在轮询状态更新,我注意到如果调用如下,则超时会持续触发:
In the application I'm building I'm polling for a status update and I have noticed that if the call is made as follows the timeout fires continuously:
setTimeout($.get("http://localhost:8080/status", function(data) { UpdateStatus(data);}), 1000);
如果使用函数而不是每1000毫秒触发超时:
While if use a function instead the timeout fires every 1000 ms:
setTimeout(function() {$.get("http://localhost:8080/status", function(data) { UpdateStatus(data);})}, 1000);
为什么?
推荐答案
在第一个示例中,您调用 $。获取
然后将其返回值传递到的setTimeout
。在第二个例子中,你根本没有调用函数;你给 setTimeout
一个它稍后会调用的函数,然后调用 $。get
为你。
In the first example, you're calling $.get
and then passing its return value into setTimeout
. In the second example, you're not calling the function at all; you're giving setTimeout
a function that it will call later, which will then call $.get
for you.
使用更简单的测试用例更容易看到:
This is easier to see with a simpler test case:
function test() {
alert("Hi there!");
}
// WRONG, *calls* `test` immediately, passes its return value to `setTimeout`:
setTimeout(test(), 1000);
// Right, passes a reference to `test` to `setTimeout`
setTimeout(test, 1000);
请注意,第一个有圆括号(()
),第二个没有。
Note that the first one has parentheses (()
), the second one doesn't.
当你想将参数传递给函数时,你必须通过定义另一个函数间接地做到这一点:
When you want to pass parameters to the function, you have to do it indirectly by defining another function:
function test(msg) {
alert(msg);
}
// WRONG, *calls* `test` immediately, passes its return value to `setTimeout`:
setTimeout(test("Hi there!"), 1000);
// Right, passes a reference to a function (that will call `test` when called) to `setTimeout`
setTimeout(function() { test("Hi there!"); }, 1000);
这篇关于在javascript中传递函数和函数调用本身之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!