/

How to Extend a Class in JavaScript: A Guide to JavaScript Inheritance

How to Extend a Class in JavaScript: A Guide to JavaScript Inheritance

JavaScript inheritance allows you to extend the functionality of a class by creating subclasses. In this guide, we’ll explore how to extend a class in JavaScript and provide specific methods and properties.

Let’s start with the base class, “Animal”:

1
2
3
4
5
class Animal {
breathe() {
//...
}
}

In this case, all animals breathe. However, not all animals can walk or fly. To handle this, we can create subclasses that extend the base class and inherit the “breathe()” method. For example, let’s create a “Fish” class that extends the “Animal” class:

1
2
3
4
5
class Fish extends Animal {
swim() {
//...
}
}

Similarly, we can create a “Bird” class that also extends the “Animal” class:

1
2
3
4
5
class Bird extends Animal {
fly() {
//...
}
}

By extending the base class, these subclasses inherit the “breathe()” method from the “Animal” class while adding their own specific methods. Now, let’s see how to instantiate instances of these classes:

1
2
const randomAnimal = new Animal();
const hummingbird = new Bird();

By using the “new” keyword, we create objects of the respective classes. This allows us to utilize the inherited methods and access the specific methods defined in each subclass.

In conclusion, extending classes in JavaScript provides a way to reuse code and create more specialized subclasses. By inheriting methods from a base class and adding specific functionalities, we can create a hierarchy of classes that accurately represent different species.

Tags: JavaScript, class inheritance, subclass, base class, methods, properties