我想我';“我误解了”;这";在JavaScript中

我想我';“我误解了”;这";在JavaScript中,javascript,Javascript,我有以下代码,应该每秒显示一次递增的数字: let timer_demo = { count: 0, timer: null, update: function() { this.count++; console.log(this.count); this.timer = setTimeout(this.update, 1000); } };

我有以下代码,应该每秒显示一次递增的数字:

    let timer_demo = {
        count: 0,
        timer: null,
        update: function() {
            this.count++;
            console.log(this.count);
            this.timer = setTimeout(this.update, 1000);
        }
    };
    timer_demo.update();
然而,当我在Chrome中运行时,我得到一个“1”,然后一秒钟后得到一个“NaN”,然后什么都没有。计时器停止。我觉得问题在于我不明白在这种情况下“这”是怎么回事。我只是不知道那是什么。第二次调用“update()”方法时,“count”字段是“NaN”,这一事实似乎支持此断言。有人能帮我解释一下吗


谢谢

函数setTimeout不调用this.update,而是获取更新函数的副本并重复它。不幸的是,它失去了对原始“this”的约束

要解决此问题,您可以执行以下操作:

let timer_demo = {
        count: 0,
        timer: null,
        update: function() {
            this.count++;
            console.log(this.count);
            this.timer = setTimeout(this.update.bind(this), 1000);
        }
    };
timer_demo.update();

这确保函数副本绑定到此上

您可以使用新的箭头函数来处理此问题。他们不绑定自己的
这个
,所以您最终会从外部环境获得它

let timer_demo = {
    count: 0,
    timer: null,
    update: () => {
        this.count++;
        console.log(this.count);
        this.timer = setTimeout(this.update, 1000);
    }
};
timer_demo.update();
在setTimeout callback中,默认情况下(在非严格模式下),此为窗口对象。要将此自定义消息传递给setTimeout回调,请使用bind


要在javascript中更好地理解这一点,请阅读。

setTimeout
未命中
this
。Try:
setTimeout(this.update.bind(this),1000)
显式设置
始终为您的对象。没错,这是解决问题的一种方法,您还可以使用箭头函数setTimeout(()=>this.update(),1000);我想你连搜索堆栈溢出都没有费心,更不用说互联网了-那里有很多信息-例如,这段代码不起作用。关于使用箭头函数,您的想法是正确的,但您在错误的地方使用了它。在这种情况下,您希望
update
属性是一个常规函数,以具有正确的
this
值。但是,对
setTimeout
的调用应该使用一个箭头函数来包装对
this的调用。update
@kamoroso94:你说得对!这种情况取决于调用方设置的
。不知道我在想什么!
var timer_demo = {
        count: 0,
        timer: null,
        update: function() {
                console.log(this);
            this.count++;
            console.log(this.count);
            this.timer = setTimeout(this.update.bind(this), 1000);
        }
 };
 timer_demo.update();