我有这段代码:
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/