Introduction

Programming paradigms such as object-oriented programming (OOP) are supported by JavaScript, a strong and adaptable programming language. Inheritance is a fundamental aspect of OOP that permits a class to inherit methods and properties from another class. JavaScript inheritance, its types, and examples with explanations will all be covered in this article.

JavaScript Inheritance

inheritance

A new class (child or subclass) can inherit attributes and methods from an existing class (parent or superclass) through the mechanism of inheritance. This creates a hierarchical relationship between classes and encourages code reuse.

Types of Inheritance in JavaScript

  1. Prototype Inheritance
  2. Class Inheritance (ES6)
  3. Mixins

Prototype Inheritance

Every object in JavaScript has a prototype. JavaScript first determines whether a property or method of an object actually exists on the object before attempting to access it. If not, the prototype chain is looked up.

As an illustration

// Parent class
function Animal(name) {
    this.name = name;
}

Animal.prototype.speak = function() {
    console.log(`${this.name} makes a noise.`);
};

// Child class
function Dog(name) {
    Animal.call(this, name); // Call the parent constructor
}

// Inherit from Animal
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

// Override the speak method
Dog.prototype.speak = function() {
    console.log(`${this.name} barks.`);
};

const dog = new Dog('Rex');
dog.speak(); // Output: Rex barks.

Prototype

Justification

Class Inheritance (ES6)

JavaScript now supports a simpler syntax for class and inheritance creation with the release of ES6.

As an illustration

class Animal {
    constructor(name) {
        this.name = name;
    }

    speak() {
        console.log(`${this.name} makes a noise.`);
    }
}

class Dog extends Animal {
    speak() {
        console.log(`${this.name} barks.`);
    }
}

const dog = new Dog('Rex');
dog.speak(); // Output: Rex barks.

Class

Justification

Mixins

Classes can gain functionality through mixins instead of inheritance. They enable you to create classes using a variety of sources.

As an illustration

const CanFly = {
    fly() {
        console.log(`${this.name} can fly.`);
    }
};

class Bird {
    constructor(name) {
        this.name = name;
    }
}

Object.assign(Bird.prototype, CanFly);

const parrot = new Bird('Polly');
parrot.fly(); // Output: Polly can fly.

Mixins

Justification

Conclusion

JavaScript inheritance is a potent feature that enables programmers to use reusable code to create intricate applications. By knowing the differences between prototype inheritance, class inheritance, and mixins, you can select the best strategy for your particular use case. You can write code for your JavaScript apps that is cleaner and easier to maintain by utilizing these ideas.

We learned the new technique and evolved together.

Happy coding!