【问题标题】:setInterval inside of a class to create an in-game clock类中的 setInterval 以创建游戏内时钟
【发布时间】:2019-11-02 17:19:10
【问题描述】:

目前我正在尝试构建一个“游戏内”时钟,可以说是我正在构建的应用程序。我想要的是创建一个 Time 类并添加一个 setInterval() 来增加 seconds 属性的时间来测试


class Time {
    constructor() {
        this.seconds = 0;
        this.countTime = setInterval(this.increaseTime, 1000)
    }

    increaseTime() {
        this.time++
        console.log(this.seconds)
    }

}

let time = new Time();

我的预期是我的函数会使用我传递的 setInterval 函数增加 this.seconds 属性。相反,它在控制台中每秒都打印出 NaN。有人知道发生了什么吗?

【问题讨论】:

标签: javascript node.js oop


【解决方案1】:

这是因为 setInterval 在全局上下文中运行回调,而 this 没有指向类。您可以在词法范围内将此绑定到此变量或使用箭头函数。

  class Time {
    constructor() {
        this.seconds = 0;
        this.countTime = setInterval(this.increaseTime.bind(this), 1000)
    }

    increaseTime() {
        this.seconds++
        console.log(this.seconds)
    }

}

let time = new Time();

【讨论】:

    猜你喜欢
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    相关资源
    最近更新 更多