对象中的属性未定义且clearInterval()无效

问题描述 投票:1回答:1

我有这段代码:

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 '3'清除间隔并打破循环。

实际发生了什么:

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

构造函数

constructor(){
    this.idMsg = 0;
    this.timerInterval;
}
  • 我修复了上面的问题,添加了一个带有代码this.idMsg = 0;的默认情况,当它到达情况3时,idMsg被设置为0但是间隔永远不会被清除,循环会一直持续开启。
javascript constructor setinterval clearinterval
1个回答
5
投票

通过将函数传递给setInterval函数,在调用它时,'this'变量会丢失上下文。所以你需要确保将combatStartLog的'this'绑定到CombatLog对象的实例:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.