Skip to content

JavaScript inheritance | Class

  • by

You can achieve JavaScript inheritance using the extends keyword with class. Using class inheritance, any class can inherit all the methods and properties of another class.

class Bird extends Animal {

        //code
    }

JavaScript inheritance is supported by using prototype objects. It’s also called by different names “Prototypal Inheritance” or “Behaviour Delegation”.

Notes:

  • Use the extends keyword to implement the inheritance in ES6.
  • Call the super(arguments) in the child class’s constructor to invoke the parent class’s constructor.
  • Use super keyword to call methods of the parent class in the methods of the child class.

JavaScript inheritance

Simple example code where class inheritance inherits all the methods from another class. Using class inheritance, a class can inherit all the methods and properties of another class.

<!DOCTYPE html>
<html>
<body>
  <script>

    // parent class
    class Person { 
      constructor(name) {
        this.name = name;
      }

      greet() {
        console.log(`Hello ${this.name} - parent Class`);
      }
    }

    // inheriting parent class
    class Student extends Person {

    }

    let student1 = new Student('John');
    student1.greet();
  </script>
</body>
</html> 

Output:

JavaScript inheritance Class

Implementing inheritance using extends and super

Use the extends keyword to make the Bird class inheriting from the Animal class. The Bird‘s constructor, call super() to invoke the Animal‘s constructor with the legs argument.

<script>

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

    Animal.prototype.walk = function() {
      console.log('walking on ' + this.legs + ' legs');
    }

    function Bird(legs) {
      Animal.call(this, legs);
    }

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


    Bird.prototype.fly = function() {
      console.log('flying');
    }

    var pigeon = new Bird(2);
    pigeon.walk(); 
    pigeon.fly(); 
</script>

Output: walking on 2 legs

flying

Uses of Inheritance

  • This allows code reusability and cleaner code and is easier to maintain.
  • Use only useful functionalities and define other required features from other classes.

Do comment if you have any doubts or suggestions on this JS class inheritance topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading