JS Inheritance

JavaScript inheritance allows one class (the child class) to inherit properties and methods from another class (the parent class). This mechanism promotes code reuse and establishes an IS-A relationship between classes.

Key Concepts

IS-A Relationship: Inheritance maintains an IS-A relationship where the child class is a specific type of the parent class.

extends Keyword: The extends keyword is used to create a subclass based on a superclass, inheriting its properties and methods.

Code Reusability: By using inheritance, you can reuse code from the parent class in the child class, avoiding duplication and improving maintainability.

Prototype-Based Inheritance: In addition to class-based inheritance, JavaScript also supports prototype-based inheritance where objects inherit directly from other objects.

JavaScript extends Example: inbuilt object

<script>
class Moment extends Date {
    constructor() {
        super();
    }
}
var m = new Moment();
document.writeln("Current date:")
document.writeln(m.getDate() + "-" + (m.getMonth() + 1) + "-" + m.getFullYear());
</script>

JavaScript extends Example: Custom class

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

    speak() {
        document.write(`${this.name} makes a noise.`);
    }
}

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

const myDog = new Dog('Rex');
myDog.speak(); // Output: Rex barks.
</script>

Prototype-Based Inheritance example:

<script>
function Animal(name) {
    this.name = name;
}

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

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

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

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

const myDog = new Dog('Rex');
myDog.speak(); // Output: Rex barks.
</script>