JavaScript class inheritance | Example code

  • by

Use the extends keyword to create a class inheritance in JavaScript. Using class inheritance, a class can inherit all the methods and properties of another class.

JavaScript class inheritance

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
      // parent class
      class Person { 
        constructor(name) {
          this.name = name;
        }

        greet() {
          console.log('Parent class')
          console.log(`Hello ${this.name}`);
        }
      }

    // inheriting parent class
    class Student extends Person {
        msg(){
          console.log('Student class')
        }
    }

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

Output:

JavaScript class inheritance

Do comment if you have any doubts or suggestions on this Js 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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.