javascript - 对象中的属性未定义且 clearInterval() 不起作用

标签 javascript constructor setinterval clearinterval

我有这段代码:

class CombatLog {
constructor(){
    this.idMsg = 0;
    this.timerInterval;
}

startTimer(){
    this.timerInterval = setInterval(this.combatStartLog, 2000);
    $('#combatLog').empty();
}

combatStartLog(){
    console.log(this.idMsg);
    switch (this.idMsg){
        case 3:
            clearInterval(this.timerInterval);
            $('#combatLog').empty();
            break;
        case 2:
            $('<p>', {
                class: 'combatText',
                id: `${this.idMsg}`
            }).appendTo('#combatLog');
            $(`#${this.idMsg}`).append(`FIGHT!`);
            this.idMsg = 3;
            break;
        case 1:
            $('<p>', {
                class: 'combatText',
                id: `${this.idMsg}`
            }).appendTo('#combatLog');
            $(`#${this.idMsg}`).append(`Prepare your potions...`);
            this.idMsg = 2;
            break;
        case 0:
            $('<p>', {
                class: 'combatText',
                id: `${this.idMsg}`
            }).appendTo('#combatLog');
            $(`#${this.idMsg}`).append(`Unsheathe your weapons...`);
            this.idMsg = 1;
        break;
        default:
            this.idMsg = 0;
    }
}

期望的行为是:

  • 我调用方法 startTimer()
  • 它调用 combatStartLog() 作为间隔
  • 每个区间对象的属性idMsg都属于对应的case
  • case '3' 清除间隔并中断循环。

实际发生了什么:

  • 我不知道为什么在第一个区间 idMsg 被实例化为 undefined,即使它的初始值是在构造函数中设置的:

构造函数

constructor(){
    this.idMsg = 0;
    this.timerInterval;
}
  • 我“修复”了上面的问题,添加了一个带有代码 this.idMsg = 0; 的默认案例,当它到达案例 3 时,idMsg 设置为 0 但间隔永远不会被清除,循环会一直持续下去。

最佳答案

通过将函数传递给 setInterval 函数,当它被调用时,“this”变量会失去上下文。因此,您需要确保将 combatStartLog 的“this”绑定(bind)到 CombatLog 对象的实例:

class CombatLog {
constructor(){
this.idMsg = 0;
this.timerInterval;
this.combatStartLog = this.combatStartLog.bind(this);}}

当您调用 new CombatLog() 时,它会调用带有“this”的构造函数作为被实例化的新对象。通过将 combatStartLog 重新分配给绑定(bind)到新对象的 combarStartLog,combatStartLog 中的“this”引用新实例化的对象。

关于javascript - 对象中的属性未定义且 clearInterval() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55349304/

相关文章:

javascript - 计算 JavaScript 中数组中元素出现的频率

c++ - 使用另一个类的函数指针

c# - 使用默认参数重载构造函数

javascript - 每秒更新一次以显示时间

javascript - CQ5 ECMA 脚本获取对服务的引用

javascript - 如何从 Firefox 插件编辑 `window` 上的属性?

javascript - 如何通过使用属性(n)的密码请求获取 Node ID?

c++ - 如何在 C++ 中显式实例化模板构造函数?

javascript - 为什么函数会在对象字面量中自调用?

javascript - 使用clearInterval方法后如何再次运行setInterval函数? - JavaScript