简体   繁体   English

在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);

While if use a function instead the timeout fires every 1000 ms: 如果使用函数而不是每1000毫秒触发超时:

 setTimeout(function() {$.get("http://localhost:8080/status", function(data) { UpdateStatus(data);})}, 1000);

Why? 为什么?

在第一个例子中, setTimeout的第一个参数被赋予$.get (错误)的结果 ,而在第二个例子中它实际上是接收一个类型为function的参数,它将被正确地评估为每个x的一组javascript语句毫秒。

In the first example, you're calling $.get and then passing its return value into setTimeout . 在第一个示例中,您将调用 $.get ,然后将其返回值传递给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. 你给setTimeout一个功能, 会再打,然后将调用$.get你。

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);

You shouldn't be passing the result of a function call to setTimeout - there's no sense in doing that. 你不应该将函数调用的结果传递给setTimeout - 这样做是没有意义的。 First argument should be the function itself, not the call. 第一个参数应该是函数本身,而不是调用。

Why it fires continuously - a strange side-effect, who knows :) 为什么它不断发射 - 一个奇怪的副作用,谁知道:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM