JS Inheritance Simplified with ES6 classes

Photo by RetroSupply on Unsplash

JS Inheritance Simplified with ES6 classes

ยท

2 min read

Lets create a class , Staff :

class Staff {
  constructor(empName, empId, dept, doj) {
    this.empName = empName;
    this.empId = empId;
    this.dept = dept;
    this.doj = doj;
  }
  //methods are added to the prototype property of the class
  empDetails() {
    console.log(
      `Emp Details : ${this.empName} works for ${this.dept} since ${this.doj}`
    );
  }
}

Now lets create another class Developer which would inherit from the parent class , Staff :

class Developer extends Staff {
  constructor(empName, empId, dept, doj, project) {
    super(empName, empId, dept, doj);
    this.project = project;
  }
  develop = function () {
    console.log(
      `${this.empName} works on ${this.project} since ${this.doj} for the department ${this.dept}`
    );
  };
}

The extends keyword is used in class declarations or class expressions to create a class that is a child of another class. It sets up the prototype chain and allows the child class to inherit properties and methods from the parent class.

The super() keyword is used to call the constructor of the parent class and to access its properties and methods. It must be called in the constructor of the child class before using this.

Now lets see how we can override a method of parent class.

class Developer extends Staff {
  constructor(empName, empId, dept, doj, project) {
    super(empName, empId, dept, doj);
    this.project = project;
  }
  develop = function () {
    console.log(
      `${this.empName} works on ${this.project} since ${this.doj} for the department ${this.dept}`
    );
  };
//overrides the parent class method empDetails
  empDetails() {
    console.log(
      `Emp Details : ${this.empName} works for the client ,IBTYN  since ${this.doj}`
    );
  }
}

Creating an instance of child class:

const smith = new Developer(
  'smith',
  2349,
  'Development',
  '9th september 1990',
  'IOS development'
);

smith.develop();
//accessing parent class methods
smith.empDetails();

Now lets assume the child class , Developer didn't have a constructor:

class Developer extends Staff {
  //
}
const smith = new Developer(
  'smith',
  2349,
  'Development',
  '9th september 1990'
);

Would this work ? Yes it would!

If the child class does not define a constructor, the parent class constructor is called automatically when creating an instance of the child class. The child class inherits the parent class constructor if no constructor is defined in the child class.

Until the next one , Break , Code , Repeat !๐Ÿ˜‰

ย