Inheritance

JavaScript Inheritance Tutorial

Table of Contents

  1. Introduction to Inheritance

  2. What is Inheritance in JavaScript?

  3. Benefits of Inheritance

  4. Implementing Inheritance Using Constructor Functions

  5. Implementing Inheritance Using ES6 Classes

  6. Overriding Methods in Inheritance

  7. Using super in JavaScript

  8. Practical Examples

    • Basic Inheritance with Constructor Functions

    • Inheritance with ES6 Classes

    • Overriding Methods in Child Classes

    • Real-World Example: Vehicle and Car Classes

  9. Conclusion


1. Introduction to Inheritance

Welcome to the Codes with Pankaj tutorial on Inheritance in JavaScript! In this tutorial, we'll explore the concept of inheritance in object-oriented programming (OOP) and how it can be implemented in JavaScript. Inheritance allows you to create new classes based on existing ones, promoting code reuse and efficiency. Let’s dive in!

2. What is Inheritance in JavaScript?

Inheritance is a mechanism in object-oriented programming that allows one class to inherit properties and methods from another class. In JavaScript, inheritance enables a new class (child class) to extend the functionality of an existing class (parent class). This allows for code reuse and creates a hierarchical relationship between classes.

3. Benefits of Inheritance

  • Code Reuse: Inheritance allows you to reuse code from a parent class, reducing duplication and making your code more maintainable.

  • Modularity: By creating a base class and extending it with specialized classes, you can break your code into smaller, more manageable pieces.

  • Flexibility: Child classes can override or extend the behavior of parent classes, allowing for customization while still retaining the base functionality.

4. Implementing Inheritance Using Constructor Functions

Before ES6, inheritance in JavaScript was typically implemented using constructor functions and the prototype property.

Example:

function Animal(name) {
    this.name = name;
}

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

function Dog(name, breed) {
    Animal.call(this, name);  // Inherit properties from Animal
    this.breed = breed;
}

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

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

let dog = new Dog("Buddy", "Golden Retriever");
dog.speak();  // Output: Buddy barks.

In this example, the Dog class inherits properties and methods from the Animal class.

5. Implementing Inheritance Using ES6 Classes

With ES6, JavaScript introduced the class syntax, making it easier to implement inheritance.

Example:

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

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

class Dog extends Animal {
    constructor(name, breed) {
        super(name);  // Call the parent class constructor
        this.breed = breed;
    }

    speak() {
        console.log(`${this.name} barks.`);
    }
}

let dog = new Dog("Buddy", "Golden Retriever");
dog.speak();  // Output: Buddy barks.

In this example, the Dog class extends the Animal class using the extends keyword. The super() function is used to call the parent class constructor.

6. Overriding Methods in Inheritance

In inheritance, a child class can override methods inherited from the parent class. This allows you to provide a specialized implementation of a method in the child class.

Example:

class Animal {
    speak() {
        console.log("The animal makes a sound.");
    }
}

class Cat extends Animal {
    speak() {
        console.log("The cat meows.");
    }
}

let cat = new Cat();
cat.speak();  // Output: The cat meows.

In this example, the speak method in the Cat class overrides the speak method in the Animal class.

7. Using super in JavaScript

The super keyword is used to call methods from a parent class. It can be used in both constructors and other methods.

Example:

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

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

class Dog extends Animal {
    constructor(name, breed) {
        super(name);  // Call the parent class constructor
        this.breed = breed;
    }

    speak() {
        super.speak();  // Call the parent class method
        console.log(`${this.name} barks.`);
    }
}

let dog = new Dog("Buddy", "Golden Retriever");
dog.speak();
// Output:
// Buddy makes a sound.
// Buddy barks.

In this example, super.speak() calls the speak method from the Animal class before adding additional behavior in the Dog class.

8. Practical Examples

Basic Inheritance with Constructor Functions

function Vehicle(make, model) {
    this.make = make;
    this.model = model;
}

Vehicle.prototype.start = function() {
    console.log(`${this.make} ${this.model} is starting.`);
};

function Car(make, model, year) {
    Vehicle.call(this, make, model);  // Inherit properties
    this.year = year;
}

Car.prototype = Object.create(Vehicle.prototype);  // Inherit methods
Car.prototype.constructor = Car;

let car = new Car("Toyota", "Camry", 2021);
car.start();  // Output: Toyota Camry is starting.

Inheritance with ES6 Classes

class Vehicle {
    constructor(make, model) {
        this.make = make;
        this.model = model;
    }

    start() {
        console.log(`${this.make} ${this.model} is starting.`);
    }
}

class Car extends Vehicle {
    constructor(make, model, year) {
        super(make, model);  // Call the parent class constructor
        this.year = year;
    }

    getCarInfo() {
        return `${this.year} ${this.make} ${this.model}`;
    }
}

let car = new Car("Honda", "Civic", 2020);
console.log(car.getCarInfo());  // Output: 2020 Honda Civic

Overriding Methods in Child Classes

class Vehicle {
    start() {
        console.log("The vehicle is starting.");
    }
}

class Motorcycle extends Vehicle {
    start() {
        console.log("The motorcycle is starting with a roar.");
    }
}

let motorcycle = new Motorcycle();
motorcycle.start();  // Output: The motorcycle is starting with a roar.

9. Conclusion

In this detailed tutorial, we've explored the concept of inheritance in JavaScript, including how to implement it using both constructor functions and ES6 classes. Inheritance allows for code reuse, modularity, and flexibility, making it a powerful tool in object-oriented programming.

For more tutorials and examples, visit www.codeswithpankaj.com! Happy coding!


Last updated