setTimeout回调参数 [英] setTimeout callback argument
问题描述
让我们考虑这段JavaScript:
Let's consider this piece of JavaScript:
function Person(name) {
this.name = name;
}
Person.prototype.showName = function() {
alert(this.name);
}
var mike = new Person("mike");
//mike.showName();
window.name = "window";
我不明白行为的区别
setTimeout(mike.showName(), 5000);
和
setTimeout(function(){
mike.showName();
}, 5000);
为什么行为会有所不同?这真让我困惑。谢谢。
Why is the behavior different? It really confuses me. Thanks.
推荐答案
您的问题确实什么都没有与有关的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.
这篇关于setTimeout回调参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!