"extends" keyword in JavaScript?


extends

'extends' keyword is used to create a class inheritance. A class created with a class inheritance will inherit all the methods from another class. Let's discuss it in a nutshell.

Example

In the following example, 'extends' keyword is used to inherit the properties from the class 'Company' to the class "model".The super() method refers to the parent class. Calling the super() method in the constructor method is nothing but calling the parent's constructor method and gets access to the parent's properties and methods.

Live Demo

<html>
<body>
<p id="method"></p>
<script>
   class Company {
      constructor(branch) {
      this.name = branch;
      }
      method() {
         return this.name + " has a product that is ";
      }
   }
   class Model extends Company {
      constructor(branch, pname) {
         super(branch);
         this.model = pname;
      }
      result() {
         return this.method() + " " + this.model;
      }
   }
   mycar = new Model("Tutorialspoint", "Tutorix");
   document.getElementById("method").innerHTML = mycar.result();
</script>
</body>
</html>

Output

Tutorialspoint has a product that is Tutorix
raja
Published on 02-Aug-2019 15:20:08
Advertisements