In the world of object-oriented programming (OOP), inheritance is a fundamental concept that enables you to create new classes based on existing ones. This concept allows you to reuse code and create hierarchical relationships between classes, making your code more efficient and easier to maintain.
With the introduction of ES6 (ECMAScript 2015), JavaScript gained support for classes, making it easier to implement inheritance using the class syntax.
In this article, we’ll explore how to use class syntax for inheritance in JavaScript, providing clear and concise examples along the way.
Creating a Parent Class
Let’s start by creating a parent class called Animal
:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
In this example, we define a constructor
method that initializes the name
property, and a speak
method that logs a message to the console.