Using Javascript inheritance, a child class can inherit all the methods and properties of another class.
To use class inheritance, you must have to use extends
keyword.
Inheritance provides the facility of code reusability.
Source Code
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
userInfo() {
document.write("Hello," + this.name + " your age is " + this.age + ".");
}
}
// inheriting parent class
class Teacher extends Person {}
let teacher1 = new Teacher("smith", 32);
teacher1.userInfo();
The javascript super
keyword is used to call the constructor of its parent class so that parent's class properties and methods can be accessed easily.
Source Code
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
document.write("Name:" + this.name + " Age: " + this.age);
}
}
class Teacher extends Person {
constructor(name, age, height) {
super(name, age);
this.height = height;
}
additionInfo() {
document.write("Your height is " + this.height);
}
}
let teacher1 = new Teacher("Jack", 25, 5);
teacher1.greet();
teacher1.additionInfo();