Saturday, 20 October 2018

JavaScript: extends: Create sub classes

‘extends’ keyword is used to create a sub class from other class. Sub classes can access the properties and methods defined in super class.

Let me explain with an example.

HelloWorld.js
class Employee{

  constructor(id, firstName, lastName){
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
  }
  
  printEmpEmpDetails(){
    console.log("id : " + this.id);
    console.log("firstName : " + this.firstName);
    console.log("lastName : " + this.lastName);
  }
  
}

class Manager extends Employee{
  constructor(id, firstName, lastName, reportees){
    super(id, firstName, lastName);
    this.reportees = reportees;
  }
  
  printEmpEmpDetails(){
    super.printEmpEmpDetails();
    console.log("Reportees : " + this.reportees);
  }
}

var reporteeIds = [123, 456, 234];

var obj1 = new Manager(4567, "Menon", "Hari", reporteeIds);

obj1.printEmpEmpDetails();

Output

id : 4567
firstName : Menon
lastName : Hari
Reportees : 123,456,234


As you see above example,
a.   Manager class extends Employee class. In this case, Employee is the super class and Manager is the sub class.
b.   If super class defines a constructor, then it must call the sub class constructor.
c.   As you see printEmpEmpDetails method of Manager class call the printEmpEmpDetails of Employee class using super keyword.
  
Extending function-based classes
Just like, how you extend class, you can even extend function-based classes.

HelloWorld.js
function Employee(id, firstName, lastName){
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
}

Employee.prototype.printEmpEmpDetails = function(){
  console.log("id : " + this.id);
  console.log("firstName : " + this.firstName);
  console.log("lastName : " + this.lastName);  
}


class Manager extends Employee{
  constructor(id, firstName, lastName, reportees){
    super(id, firstName, lastName);
    this.reportees = reportees;
  }
  
  printEmpEmpDetails(){
    super.printEmpEmpDetails();
    console.log("Reportees : " + this.reportees);
  }
}

var reporteeIds = [123, 456, 234];

var obj1 = new Manager(4567, "Menon", "Hari", reporteeIds);

obj1.printEmpEmpDetails();


Output
id : 4567
firstName : Menon
lastName : Hari
Reportees : 123,456,234



Previous                                                 Next                                                 Home

No comments:

Post a Comment