Articles → JAVASCRIPT → Class inheritance in JavaScript

Class inheritance in JavaScript






Example




<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
   <head>
      <meta charset="utf-8" />
      <title></title>
      <script>
         class BaseClass {
             Print() {
                 alert("Print message of the BaseClass");
             }
         }
         
         class DerivedClass extends BaseClass {
             Print1() {
                 alert("Print message of the Derived Class");
             }
         }
         
         let cls = new DerivedClass();
         cls.Print();
         cls.Print1();
      </script>
   </head>
   <body>
   </body>
</html>




Picture showing the output of class inheritance in javascript

Click to Enlarge

Picture showing the output of class inheritance in javascript

Click to Enlarge


Calling the constructors of base and derived class




<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
   <head>
      <meta charset="utf-8" />
      <title></title>
      <script>
         class BaseClass {
             constructor() {
                 alert("Constructor of the base class");
             }            
         }
         
         class DerivedClass extends BaseClass {
             constructor() {
                 super();
                 alert("Constructor of the derived class");
             }
         }
         
         let cls = new DerivedClass();
         
      </script>
   </head>
   <body>
   </body>
</html>




Picture showing the output of calling the constructor in Javascript

Click to Enlarge

Picture showing the output of calling the constructor in Javascript

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, July 29, 2021

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250