override a property on a subclass in javascript

To override a property on a subclass in JavaScript, you can define the property again in the subclass using the super keyword to access the superclass's version of the property.

Here is an example:

index.tsx
class Animal {
  constructor(name) {
    this.name = name;
    this.type = 'unknown';
  }
}

class Cat extends Animal {
  constructor(name) {
    super(name);
    this.type = 'cat';
  }
}

const myCat = new Cat('Fluffy');

console.log(myCat.name); // 'Fluffy'
console.log(myCat.type); // 'cat'
294 chars
19 lines

In this example, the Animal class has a type property set to 'unknown'. The Cat subclass extends Animal and overrides the type property by defining it again in the constructor using the super keyword to access the type property from the Animal class. When we create a new Cat instance and log its type property, we get 'cat' instead of 'unknown'.

gistlibby LogSnag