且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

setTimeout回调参数

更新时间:2023-11-30 22:15:52

您的问题确实什么都没有有关的setTimeout 。您只需要了解函数调用和函数引用之间的区别。

Your question really has nothing at all to do with setTimeout. You simply need to understand the difference between a function call and a reference to a function.

考虑这四个分配:

var one = function() { mike.showName(); };
var two = mike.showName;
var three = mike.showName();
var four = (function() { mike.showName(); })();

前两个将函数的引用分配给它们各自的变量。然而,最后两个调用函数(这就是parens的用途)并将它们的返回值分配给左侧的变量。

The first two assign a reference to a function to their respective variables. The last two, however, call functions (that's what the parens are for) and assign their return values to the vars on the left-hand side.

这与setTimeout的关系如何:

setTimeout 函数需要作为其第一个参数引用到一个函数,所以上面的一个两个是正确的,但不会。但是,重要的是要注意,严格来说,错误并不是将函数的返回值传递给 setTimeout ,尽管你经常会看到这样说。

The setTimeout function expects as its first argument a reference to a function, so either one or two above would be correct, but three and four would not. However, it is important to note that it is not, strictly speaking, a mistake to pass the return value of a function to setTimeout, although you'll frequently see that said.

这很好,例如:

function makeTimeoutFunc(param) {
    return function() {
        // does something with param
    }
}

setTimeout(makeTimeoutFunc(), 5000);

它与如何 setTimeout无关接收一个函数作为其参数,但它接收

It has nothing to do with how setTimeout receives a function as its argument, but that it does.