Javascript ES6/ES2015

Example of inheritiance in javascript using ES6/ES2015

The following Person class is created using ES6 syntax

   
              class Person {
                    constructor(firstname,lastname){
                        this.firstname = firstname;
                        this.lastname = lastname;
                    }
                    sayHello(){
                        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 {
                    constructor(firstname,lastname,school,major){
                    super(firstname,lastname);
                    this.major = major;
                    this.school = school;
                    }
                    sayHello(){
                        console.log(`Hello my name is ${this.firstname} ${this.lastname} majoring in ${this.major} at ${this.school}!`);
                    }
                }
               

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');
                anna.sayHello();

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

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.





Services
  • SEO
  • Online Advertising
  • Online Ordering For Restaurants
  • Data Analytics

  • External Resources 4 Developers
  • CSS Tricks
  • MDN

  • Dash-Intel.com is a Power BI and Tableau resource site around data visualizations and building business dashboards.

    Data Analytics consultants in Edmonton, Alberta specializing in Tableau and marketing analytics

    Copyright 2020 Dash-Intel.com Terms / All rights reserved.