JavaScript Inheritance

JavaScript Class Inheritance allows to create a new class that inherits properties and methods from an existing class. The new class is called a subclass, and the existing class is called a superclass. This tutorial will teach you how to use inheritance in JavaScript.

Declaring a Superclass (parent class)

To declare a superclass in JavaScript, you create a class using the class keyword. Here's an example of a simple superclass:

1class Animal { 2 constructor(name) { 3 = name; 4 } 5 6 speak() { 7 console.log(`${} makes a sound.`); 8 } 9}

In this example, a class Animal is declared with a constructor that takes a single parameter name and sets it as an object property. The class also has a method speak that logs a message to the console.

Declaring a Subclass (child class)

To declare a subclass in JavaScript, you use the extends keyword to inherit from a superclass. Here's an example of a subclass:

1class Dog extends Animal { 2 constructor(name, breed) { 3 super(name); 4 this.breed = breed; 5 } 6 7 bark() { 8 console.log(`${} barks.`); 9 } 10}

In this example, a new class Dog is declared that extends the Animal class. The Dog class has a constructor that takes two parameters name and breed, and sets them as object properties. The super keyword is used to call the constructor of the Animal class and set the name property. The Dog class also has a new method bark that logs a message to the console.

Creating an Object from a Subclass

To create an object from a subclass, you use the same new keyword as with a regular class. Here's an example:

1let dog = new Dog("Buddy", "Labrador"); 2dog.speak(); // Buddy makes a sound. 3dog.bark(); // Buddy barks.

In this example, a new object dog is created from the Dog class, and its name and breed properties are set to "Buddy" and "Labrador", respectively. The object can access the speak method inherited from the Animal class and the bark method defined in the Dog class.

Overriding Methods

A subclass can override a method inherited from a superclass by declaring a new method with the same name. Here's an example extending child class(act as parent to next child) to another child class:

1class Dog2 extends Dog { 2 bark() { 3 console.log(`${} barks loudly.`); 4 } 5} 6 7let dog2 = new Dog2("Rufus", "Jack Russell Terrier"); 8dog2.speak(); // Rufus makes a sound. 9dog2.bark(); // Rufus barks loudly.

In this example, a new class Dog2 is declared that extends the Dog class. The Dog2 class overrides the bark method from the Dog class and provides a new implementation that logs a different message to the console