Understanding JavaScript Class Inheritance For Absolute Beginners

Posted on : 2024-03-20
Understanding JavaScript Class Inheritance For Absolute Beginners

Share

One of the key features of OOP is inheritance, which allows you to create new classes based on existing classes. In this article, we'll explore the basics of JavaScript inheritance and how you can use it in your projects.

What is Inheritance in JavaScript?

Inheritance is a mechanism in JavaScript that allows a new class to inherit properties and methods from an existing class. This enables you to create a hierarchy of classes, with each new class inheriting characteristics from its parent class.

Creating a Parent Class

To create a parent class in JavaScript, you define a class using the class keyword. For example, let's create a Shape class with a color property and a draw method:

class Shape {
  constructor(color) {
    this.color = color;
  }

  draw() {
    console.log(`Drawing a ${this.color} shape.`);
  }
}

Creating a Child Class

To create a child class that inherits from a parent class, you use the extends keyword followed by the name of the parent class. For example, let's create a Circle class that inherits from the Shape class:

class Circle extends Shape {
  constructor(color, radius) {
    super(color);
    this.radius = radius;
  }

  draw() {
    console.log(`Drawing a ${this.color} circle with radius ${this.radius}.`);
  }
}

Using the Child Class

Once you have defined a child class, you can create objects (instances) of that class just like any other class. For example, to create a new Circle object with a color of "red" and a radius of 5, you would write:

let circle = new Circle("red", 5);
circle.draw();

Understanding the super Keyword

In the child class constructor, the super keyword is used to call the parent class constructor and pass any necessary arguments. This is required when the parent class has a constructor that needs to be called with specific values.