🍆Class Inheritance
In JavaScript, class inheritance is a way for one class to inherit the properties and methods of another class. It is a way to create a new class that is a modified version of an existing class, without having to rewrite all of the code in the new class.
To create a class that inherits from another class, you use the extends
keyword and specify the parent class. The new class is called the child class, and the class it inherits from is the parent class. Here is an example of class inheritance in JavaScript:
In this example, we have a base Animal
class with a name
, speak
method, and getters and setters for the name
property. The Dog
class extends the Animal
class and adds a breed
property and its own implementation of the speak
method. The Dog
class uses the super
keyword to call the constructor of the parent class and pass along the name
argument.
The Dog
class inherits the name
property and getters and setters from the Animal
class, and it also has its own breed
property and speak
method. When we create an instance of the Dog
class and call its speak
method, it uses the speak
method that was defined in the Dog
class, rather than the one defined in the Animal
class.
Last updated