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

Property in object is undefined and clearInterval() not working

我有这段代码:

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;
    }
}

期望的行为是:

实际发生了什么:

构造函数

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

通过将函数传递给 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' 引用新实例化的对象。