我有这段代码:
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但是间隔永远不会被清除,循环会一直持续开启。通过将函数传递给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”指向新实例化的对象。