We have seen how to create Classes in JavaScript.
Let’s now learn how to inherit classes in JavaScript.
- In inheritance, parameters and methods of base class can be used in derived class.
- We inherit class using extend keyword.
- constructor is a default function which is automatically called when a class is instantiated. It is used to initialize the parameters of the class.
- super is a method that is used to call base class’ constructor.
- this keyword is used to access the parameters for current object.
Below is a sample code for inheritance
class Person{
constructor(personName, personAddress){
this.name=personName;
this.address=personAddress;
}
getPersonDetails(){
console.log("Name: " + this.name);
console.log("Location: " + this.address);
}
}
class Student extends Person{
constructor(name, address,studentClass, studentId){
super(name, address);
this.studentClass = studentClass;
this.Id=studentId;
}
getStudentDetails(){
console.log("Class: " + this.studentClass);
console.log("ID: " + this.Id);
}
}
class CollegeStudent extends Student{
constructor(name, address, stdCls, id, clgName){
super(name, address, stdCls, id);
this.CollegeName=clgName;
}
getDetails(){
console.log("College Name: " + this.CollegeName);
}
}
const student = new CollegeStudent("Akanksha","Delhi","12th",12345,"NIT");
student.getPersonDetails();
student.getStudentDetails();
student.getDetails();

