【问题标题】:Why is an anonymous function required to preserve "this" using setTimeout为什么需要匿名函数来使用 setTimeout 保留“this”
【发布时间】:2014-01-29 11:08:46
【问题描述】:

我已经多次使用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"
};

【问题讨论】:

  • The "this" problem: 由 setTimeout() 执行的代码运行在与调用它的函数不同的执行上下文中。因此,被调用函数的 this 关键字将被设置为窗口(或全局)对象;它与调用 setTimeout 的函数的 this 值不同。
  • 不确定这是否完全是骗局,但似乎很相似:stackoverflow.com/questions/1101668/…

标签: javascript settimeout


【解决方案1】:

这不起作用,因为setTimeout 调用了具有this 值的函数作为全局对象,而不是父对象。您正在将一个值传递给setTimeout 函数——它不知道它是如何被访问的,因此无法使用正确的this 值调用它(与普通变量不同,this 的值只是确定的调用函数时,除非this 已使用Function.prototype.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?

【讨论】:

    【解决方案2】:

    因为在第一种情况下,您只引用了that 对象内的函数log,但它与that 的关系丢失了。可以把它想象成setTimeout 在全局上下文的存储内存地址处直接调用log 方法。

    然而,在第二个示例中,您来自全局上下文,但首先查找 that,然后使用 that 的上下文调用 log。

    认为 setTimeout 具有以下结构:

    var setTimeout = function (func, time) {
       someWaitMechanism(time, function () { //this is called after the timeout
           func.call(null); //calls func with global scope
       });
    }
    

    【讨论】:

    • func.call(null) 和 func() 不会有什么不同,对吧?你可能想明确一点;)
    • 只是想强调 thisArg 设置为 null,因此是全局上下文,但你是对的 :)
    • 确实,这可能不是那么明显:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多