繁体   English   中英

为什么需要匿名函数来使用setTimeout保留“this”

[英]Why is an anonymous function required to preserve “this” using setTimeout

我已经多次使用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 )。

通过改变一个匿名函数,您使用的封闭访问的价值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

还有使用一个相关的问题thissetTimeout传递正确的“这个”背景下的setTimeout回调?

因为在第一种情况下,你只引用功能log那是内that物体,但其关系that丢失。 可以把它想象成setTimeout直接调用存储的内存地址中的log方法和全局上下文。

在第二个例子但是你来自全球范围内,但首先that是抬头,事后log其与上下文称为然后that

可以认为setTimeout具有以下结构:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM