Role-playing game example
Here is an example of using instance methods in the context of a role-playing video game:
class Character {
constructor(name, hp, attackPower) {
this.name = name;
this.hp = hp;
this.attackPower = attackPower;
}
// Instance method to attack another character
attack(otherCharacter) {
otherCharacter.hp -= this.attackPower;
console.log(`${this.name} attacked ${otherCharacter.name} for ${this.attackPower} damage!`);
}
// Instance method to heal this character
heal(amount) {
this.hp += amount;
console.log(`${this.name} healed for ${amount} HP!`);
}
}
class Warrior extends Character {
constructor(name, hp, attackPower, shield) {
super(name, hp, attackPower);
this.shield = shield;
}
// Override the attack method to include the shield value
attack(otherCharacter) {
const totalAttackPower = this.attackPower + this.shield;
otherCharacter.hp -= totalAttackPower;
console.log(`${this.name} attack ${otherCharacter.name} for ${totalAttackPower} damage!`);
}
}
class Mage extends Character {
constructor(name, hp, attackPower, magicPower) {
super(name, hp, attackPower);
this.magicPower = magicPower;
}
// Instance method to cast a spell on another character
castSpell(otherCharacter) {
otherCharacter.hp -= this.magicPower;
console.log(`${this.name} casts a spell on ${otherCharacter.name} for ${this.magicPower} damage!`);
}
}
const warrior1 = new Warrior('Bob', 100, 10, 5);
const mage1 = new Mage('Alice', 80, 5, 15);
warrior1.attack(mage1); // "Bob attack Alice for 15 damage!"
mage1.castSpell(warrior1); // "Alice casts a spell on Bob for 15 damage!"
warrior1.heal(10); // "Bob healed for 10 HP!"
n this example, we have a base Character
class with an attack
method that reduces the hit points (HP) of another character, and a heal
method that increases the character's own HP. We also have a Warrior
class that extends the Character
class and has a shield
property, and an attack
method that includes the shield value in the attack power. Finally, we have a Mage
class that extends the Character
class and has a magicPower
property, and a castSpell
method that reduces the HP of another character using the magic power.
We create a warrior and a mage character, and use their instance methods to attack and cast spells on each other. The warrior also uses the heal
method to restore some of its own HP.
Last updated