override a method on a subclass in javascript

To override a method on a subclass in JavaScript, you can simply create a new method with the same name as the parent method. In order to call the parent method from within the subclass method, you can use the super keyword.

Here's an example:

index.tsx
class Animal {
  makeSound() {
    console.log("generic animal sound");
  }
}

class Dog extends Animal {
  makeSound() {
    super.makeSound();
    console.log("bark");
  }
}

const myDog = new Dog();
myDog.makeSound(); // Output: "generic animal sound" followed by "bark"
274 chars
16 lines

In this example, we have a parent class Animal with a method makeSound that logs a generic animal sound to the console. We then create a subclass Dog that extends Animal, and overrides the makeSound method to also log "bark" to the console.

Within the Dog class, we call the makeSound method of the Animal class using super.makeSound(), and then add our own logic to log "bark". When we create a new instance of Dog and call makeSound(), we'll see both "generic animal sound" and "bark" logged to the console.

gistlibby LogSnag