Modern JavaScript
About Lesson

In this JavaScript lesson we are going to talk about JavaScript Class Inheritance, also we will learn that how you can use method overriding in JavaScript, so class inheritance is the mechanism of basing an object or class upon another object or class, retaining similar implementation. Also defined as deriving new classes from existing ones such as super class or base class and then forming them into a hierarchy of classes.

 

 

Now let’s create an example of class inheritance. in this code we have two classes the first one is our Animal class and it is our base class, we have another Dog class that extends from the Animal base class, if you see the Animal class we have a function of speak(). now our Dog class after extending from the Animal class can access to this function.

 

 

 

Also you can do method overriding, for example if you want to change the functionality of the speak() function in your extended class than you can use method overriding.

 

 

JavaScript Class Inheritance Features

As we already mentioned that Class inheritance in JavaScript allows you to define subclass that inherits from parent class, along with all of its properties and methods. these are some features of JavaScript class inheritance along with code examples:

 

  1. Class Declaration: You can define class using the class keyword followed by the class name.

In this example Animal class is defined with constructor and speak method. An instance of the Animal class is created and the speak method is called.

 

  1. Inheritance: You can create a subclass that inherits from a parent class using the extends keyword.

In this example Dog class is defined as subclass of Animal. The Dog class has constructor that calls the parent constructor using the super keyword. Dog class also overrides the speak method to make the dog bark.

 

 

  1. Accessing Parent Class Methods: You can access parent class methods in the subclass using the super keyword.

In this example Cat class is defined as subclass of Animal. The Cat class has constructor that calls the parent constructor using the super keyword. Cat class overrides the speak method to make the cat meow but it also calls the parent speak method to make the cat make a noise.

 

 

  1. Multiple Inheritance: JavaScript does not support multiple inheritance but you can simulate it using mixins or by using composition instead of inheritance.

 

 

In conclusion we can say that class inheritance in JavaScript is powerful feature that can help you create complex and organized code. It allows you to create reusable code that can be shared between multiple classes and reduces the amount of code duplication.