'I need to decrease a value of the property only from specific class objects
I have three classes and two of them inheriting from an Animal class, Carnivore class should have method to decrease health by 50 if I call the method on Herbivore objects only. How to write a correct condition in my case so i won't touch unneeded objects?
class Animal {
static alive = [];
constructor(name, health) {
this.name = name;
this.health = health || 100;
}
}
class Herbivore extends Animal {
constructor(name, health) {
super(name, health);
this.hidden = false;
Animal.alive += [this];
}
hide() {
if (this.hidden === false) {
this.hidden = true;
} else {
this.hidden = false;
}
return this;
}
}
class Carnivore extends Animal {
constructor(name, health) {
super(name, health);
Animal.alive += [this];
}
bite() {
// if ???
this.health = this.health - 50;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|