问题描述
我正在编写一个程序,其中一个类对象有许多方法 - 例如这个:
heal() {
console.log(`The ${this.type} heals itself!`);
consoleSpan.innerHTML = `The ${this.type} heals itself!`;
consoleSpan.innerHTML += `<br><br>The ${this.type} gets +3 health`
this.health += 3;
refresh();
changeTurn();
}
这很好用。但是我想稍微延迟一下,以便我可以在值和文本更新之前添加一些动画,但是当我尝试时它不再起作用。如果我这样做:
heal() {
setTimeout(function(){
console.log(`The ${this.type} heals itself!`);
consoleSpan.innerHTML = `The ${this.type} heals itself!`;
consoleSpan.innerHTML += `<br><br>The ${this.type} gets +3 health`
this.health += 3;
refresh();
changeTurn();
},500);
}
然后 this.type 不起作用,例如它的控制台日志记录“undefined 自愈!”
我认为它在函数中添加一个函数会以某种方式阻止this.工作,但我不知道如何解决这个问题。
如果有用,这里是该类对象的完整代码:
class character {
constructor(type,health,damage,defence,poweredUp,shieldUp) {
this.type = type;
this.health = health;
this.damage = damage;
this.defence = defence;
poweredUp = false;
shieldUp = false;
}
attack() {
console.log(`The ${this.type} attacks!`);
consoleSpan.innerHTML = `The ${this.type} attacks!`;
if ((this.damage - this.opponent.defence) <= 0) {
this.opponent.health --;
consoleSpan.innerHTML += `<br><br>The ${this.type} does 1 damage.`;
} else {
this.opponent.health -= (this.damage - this.opponent.defence);
consoleSpan.innerHTML += `<br><br>The ${this.type} does ${(this.damage - this.opponent.defence)} damage.`;
}
if (this.poweredUp == true) {
this.damage -= 3;
this.poweredUp = false;
}
if (this.opponent.shieldUp == true) {
this.opponent.shieldUp = false;
this.opponent.defence -= 3;
}
refresh();
changeTurn();
if (this.opponent.health <= 0) {
death();
}
}
heal() {
console.log(`The ${this.type} heals itself!`);
consoleSpan.innerHTML = `The ${this.type} heals itself!`;
consoleSpan.innerHTML += `<br><br>The ${this.type} gets +3 health`
this.health += 3;
refresh();
changeTurn();
}
powerUp() {
if (this.poweredUp == true) {
console.log("Already powered up!")
} else {
console.log(`The ${this.type} is powering up!`);
consoleSpan.innerHTML = `The ${this.type} is powering up!`;
consoleSpan.innerHTML += `<br><br>The ${this.type} gets +3 damage`
this.damage += 3;
this.poweredUp = true;
}
refresh()
changeTurn();
}
raiseShield() {
if (this.shieldUp == true) {
console.log("Shield's already up!");
} else {
console.log(`The ${this.type} puts up its shield!`);
consoleSpan.innerHTML = `The ${this.type} puts up its shield!`;
consoleSpan.innerHTML += `<br><br>The ${this.type} gets +3 defence`
this.defence += 3;
this.shieldUp = true;
}
refresh();
changeTurn();
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)