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.tsx274 chars16 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