Open In App

Which keywords can be used to implement inheritance in ES6 ?

In this article, we will discuss the keywords that can be used to implement inheritance in es6?In JavaScript, the “extends”, “this” and “super ” keywords are used to implement inheritance.

Extends keyword: To construct a class that is a child of another class, use the extends keyword in class declarations or class expressions. The parent class’s methods are passed down to the child class.



let’s demonstrate a few examples of these keywords.

Example 1: In this example, the apple class extends from the fruits class, as we don’t use this keyword in console.log(), the values in the array of parent class are not used in the child class. 






<script>
  class fruits {
    constructor(benefits) {
      this.benefits = ["vitamins", "minerals"];
    }
  }
  class apple extends fruits {
    constructor(benefits) {
      super(benefits);
      console.log("apples provide : " + benefits.join(" and "));
    }
  }
  obj = new apple(["fibre", "lung strength"]);
</script>

Output:

apples provide : fibre and lung strength

Example 2: This code is similar to the before one but the difference is after using the super method on the benefits array, we use this keyword, which points out to the array defined in the parent class.




<script>
  class fruits {
    constructor(benefits) {
      this.benefits = ["vitamins", "minerals"];
    }
  }
  class apple extends fruits {
    constructor(benefits) {
      super(benefits);
      console.log("apples provide : " +
                  this.benefits.join(" and "));
    }
  }
  obj = new apple(["fibre", "lung strength"]);
</script>

Output:

apples provide : vitamins and minerals

Example 3: In the below example, we define a class that has certain methods. penguin class extends from parent class i.e birds which has another method swim(). The penguin class contains all methods from the parent class. Let’s understand how to use “this”, “super”, and “extends” keywords in this example.




<script>
   class birds {
     constructor(name) {
       this.name = name;
     }
     eat() {
       console.log("birds eat");
     }
     sleep() {
       console.log("birds sleep");
     }
   }
   class penguin extends birds {
     constructor(name) {
       super(name);
     }
     swim() {
       console.log("I'm " + this.name + 
                   " i can also swim!!");
     }
   }
   obj = new penguin("peggy");
   obj.swim();
   obj.sleep();
</script>

Output:

"I'm peggy i can also swim!!"
"birds sleep"

Article Tags :