🥑Use of Super
In JavaScript, the super keyword is used to call the parent class's constructor or a method from the child class. For example, consider the following code:
In this example, the Cat
class extends the Animal
class and overrides the speak
method. The Cat
class also has a constructor that accepts a name
and a breed
parameter. In the Cat
constructor, we use the super
keyword to call the Animal
constructor and pass it the name
argument. This sets the name
property of the Cat
instance to the value of the name
argument.
The super
keyword can also be used to call a method of the parent class from the child class. For example, we could modify the speak
method of the Cat
class to call the speak
method of the Animal
class like this:
This would cause the Cat
instance to make both a noise (using the speak
method from the Animal
class) and meow (using the speak
method from the Cat
class).
Last updated