Here is an example of using instance methods in the context of a role-playing video game:
classCharacter {constructor(name, hp, attackPower) {this.name = name;this.hp = hp;this.attackPower = attackPower; }// Instance method to attack another characterattack(otherCharacter) {otherCharacter.hp -=this.attackPower;console.log(`${this.name} attacked ${otherCharacter.name} for ${this.attackPower} damage!`); }// Instance method to heal this characterheal(amount) {this.hp += amount;console.log(`${this.name} healed for ${amount} HP!`); }}classWarriorextendsCharacter {constructor(name, hp, attackPower, shield) {super(name, hp, attackPower);this.shield = shield; }// Override the attack method to include the shield valueattack(otherCharacter) {consttotalAttackPower=this.attackPower +this.shield;otherCharacter.hp -= totalAttackPower;console.log(`${this.name} attack ${otherCharacter.name} for ${totalAttackPower} damage!`); }}classMageextendsCharacter {constructor(name, hp, attackPower, magicPower) {super(name, hp, attackPower);this.magicPower = magicPower; }// Instance method to cast a spell on another charactercastSpell(otherCharacter) {otherCharacter.hp -=this.magicPower;console.log(`${this.name} casts a spell on ${otherCharacter.name} for ${this.magicPower} damage!`); }}constwarrior1=newWarrior('Bob',100,10,5);constmage1=newMage('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.