我已经多次使用 setTimeout
传递函数作为引用,例如
setTimeout(someFunction, 3000);
在某些情况下,为了保留 this
的值,我不得不事先将其分配给一个变量,但不明白为什么以下内容不起作用:
var logger = {
log: function() {
var that = this;
console.log(that.msg);
setTimeout(that.log, 3000);
},
msg: "test"
};
logger.log();
然而,使用匿名函数确实有效:
var logger = {
log: function() {
var that = this;
console.log(that.msg);
setTimeout(function() { that.log() }, 3000);
},
msg: "test"
};
最佳答案
这不起作用,因为 setTimeout
调用一个函数,将 this
值作为全局对象,而不是父对象。您正在将一个值传递给 setTimeout
函数——它不知道它是如何被访问的,因此无法使用正确的 this
值调用它(与普通变量不同,this
的值仅在调用函数时确定,除非 this
已使用 Function.prototype.bind
绑定(bind)到特定值).
通过将它更改为匿名函数,您可以使用闭包访问 that
的值,即使是作为值调用(函数的变量范围在定义时设置) ,而不是在运行时)。
就像你做这样的事情一样:
var a = { b: function () { return this.foo; }, foo: 'proper' };
function test(arg) {
return arg();
}
var foo = 'random';
console.log(a.b()); // proper
console.log(test(a.b)); // random
还有一个关于将 this
与 setTimeout
一起使用的相关问题:Pass correct "this" context to setTimeout callback?
关于javascript - 为什么需要匿名函数来使用 setTimeout 保留 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21429255/