Inheritance in JavaScript
Inheritance in JavaScript
Welcome back! Now that you have a solid understanding of classes and objects in JavaScript, it's time to delve deeper into inheritance. This is a natural progression in our journey into object-oriented programming (OOP) using JavaScript's unique syntax and features.
Inheritance in JavaScript allows you to create a new class that reuses the behavior of an existing class via prototypes. This facilitates code reuse, extends object functionalities, and creates easily manageable and understandable programs. Let's dive in!
What We'll Cover
In this lesson, you'll understand how to leverage inheritance in JavaScript. We'll cover:
- What Inheritance Is in JavaScript
- How to Implement Inheritance Using ES6 Classes
- Benefits of Using Inheritance
You'll also learn about the prototype chain and how to manage inheritance using classes and constructors.
What Inheritance Is
Inheritance in JavaScript is a mechanism to create a hierarchical class structure through a prototype chain, whereby one object inherits the properties and methods of another. To better understand this, we’ll use an example involving a Person class as the base class and a Student class as the derived class. This will help you see how properties and methods are inherited and extended in JavaScript.
Base Class: Person
Let’s start by defining a Person class using ES6 class syntax to act as the base class in our example:
In this snippet, the Person class is defined with attributes name and age. The constructor initializes these attributes, and a display method is used to print the details.
Derived Class: Student
Now, we’ll create a Student class that extends the Person class:
In the Student class, we use the extends keyword to inherit from Person. The constructor uses the super function to call the base class constructor, initializing the inherited properties. The Student class adds a new attribute major and a displayMajor method specific to its class.
