问题描述
我只是想知道;
为什么这样做?
test = function(message) {
console.log('xxx');
}
setTimeout(test, 3000);
但这不是;
test = function(message) {
console.log(message);
}
setTimeout(test('xxx'), 3000);
我知道应该这样写; 但是上面的版本会方便得多...
test = function(message) {
console.log(message);
}
setTimeout(function() { test('xxx'); }, 3000);
1楼
1
已采纳
您要将test
的返回结果分配给setTimeout
的回调参数,而不是传递函数引用。
function callback(callback) {
callback();
}
function say(message) {
console.log(message);
// this function doesn't return anything
}
// callback(say('Hello World!')) === callback() because say(message) doesnt return anything.
2楼
Daniel A. White
0
2015-07-26 01:19:30
在您的第二个示例中,它立即使用字符串xxx
调用test
。
3楼
chris p bacon
0
2015-07-26 01:20:57
在第二个示例中,您将立即调用该函数。
要传递字符串,可以bind
参数,而不是单独调用它:
setTimeout(test.bind(null,'xxxx'), 3000);
test = function(message) { alert(message); } setTimeout(test.bind(null,'xxxx'), 3000);
4楼
sylvain1264
0
2015-07-26 01:21:04
如果用括号写一个函数名,它将调用它而不是提供引用。
5楼
Michael
0
2015-07-26 01:22:00
第二个不起作用,因为setTimeout需要一个函数作为参数(它将调用该函数),并且您显示的第二个版本具有te??st('xxx'),这意味着“调用test('xxx')的结果”未定义- 不是函数。