Javascript ES6/ES2015

Example of inheritiance in javascript using ES6/ES2015

The following Person class is created using ES6 syntax

              class Person {
                        this.firstname = firstname;
                        this.lastname = lastname;
                        console.log(`Hello my name is ${this.firstname} ${this.lastname}!`);

This Person class has the properties of firstname and lastname as defined in the constructor function. It also has the sayHello method.

Next, the class Student will inherit all the properties and methods of the Person class. This is done using the extends keyword. The super keyword is used to access and call the parents constructor. In this case, the Parent is the Person class.

              class Student extends Person {
                    this.major = major;
           = school;
                        console.log(`Hello my name is ${this.firstname} ${this.lastname} majoring in ${this.major} at ${}!`);

The arguments of super are only the parents constructor, and the arguments of the constructor function are all the properties of the student class. Two new properties of the student we must declare them as shown above.

Try it out

Try out the code above by creating an instance of the the classes above.


             // create a new person instance
                const anna = new Person('Anna','Maluk');

                //create a new student instance
                const ava = new Student('Ava', 'Ivanovic','University of Belgium','Psychology');

Note: The class keyword is just another way to create function constructors and prototype methods using ES5 syntax. Classes are syntactic sugar. Classes in javascript, under the hood, are really just functions and objects. When using classes, we can use the concept of inheritance by using extends and super keywords.

Dash-Intel is a Power BI and Tableau resource site for data visualization and building BI dashboards.

Data Analyst & Consultant

Copyright 2015-2023 Terms