override a static property on a subclass in javascript

To override a static property on a subclass in JavaScript, you can simply declare the static property with the same name in the subclass. Here's an example:

index.tsx
class Animal {
  static species = 'unknown';
  
  static getSpecies() {
    return this.species;
  }
}

class Cat extends Animal {
  static species = 'cat';
}

console.log(Animal.getSpecies()); // output: "unknown"
console.log(Cat.getSpecies()); // output: "cat"
263 chars
15 lines

In the above example, we have a parent class Animal with a static property species set to "unknown". We then define a subclass Cat which extends Animal and overrides the species property with "cat". We can access the static properties of each class by calling getSpecies() on them.

When we call Animal.getSpecies(), it returns "unknown", and when we call Cat.getSpecies(), it returns "cat". This is because the species property is defined on both the parent Animal class and the child Cat class, but the child class takes precedence.

gistlibby LogSnag