Thursday, August 29, 2019

JavaScript Class : The super and extends keywords

In blog, we learn about JavaScript class and how to implement inheritance by using supper and extends keyword

The keyword extends is used to implement the inheritance in JavaScript class and we can create a subclass or child class by using the ‘extends’ keyword. In inheritance, the child class is derived with base class and has own extra business logic.


Here is an example which demonstrates how to inherit Person Class and create an Employee Class.

  class Person {
        constructor(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;         
        }

        name() {
            return this.firstName + ' ' + this.lastName;
        }
    };

    class Employee extends Person {
        constructor(firstName, lastName, employeeID, department) {        
            super(firstName, lastName);
            this.employeeID = employeeID;
            this.department = department;
        }     
    };

The keyword ‘super’ is used to call the constructor method of base class. The child class has always a constructor method, it should call to super() method to invoke base class constructor method and initialize the properties of base class.

    var _person = new Employee("Henry", "Ford", 100, "IT");

    console.log(_person.name()); 
    console.log(_person.department);

Console message:

Henry Ford
IT

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...