I'm making a program where an class object has a number of methods - for instance this one:
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();
}
This works fine. But I'm wanting to make a slight delay so that I can add in some animations before the values and text update, but when I try that it no longer works. If I do this:
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);
}
Then the this.type isn't working, and for instance it's console logging "The undefined heals itself!"
I assume the fact that it's adding a function within a function is somehow stopping this. from working, but I can't work out how to get around that.
If useful, here's the full code for that class object:
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();
}
}