JavaScript Inheritance

The property of acquiring all the properties and behaviors of the parent object by an object is termed as inheritance. This is a unique feature in object oriented programming languages which facilitates re-usability of the code of the parent class by the derived class. In JavaScript, extends keyword is used to serve the purpose of inheritance.

Inheritance is used to maintain the IS-A relationship between objects.

Example:

<!DOCTYPE html>
<html>
<body>
 
<script>
class Time extends Date {
  constructor(month) {
	super(month);
  }}
var m=new Time("November 16,1994 20:22:10");
document.writeln("Month value:")
document.writeln(m.getMonth()+1);
</script>
 
</body>
</html>

Output:

Month value: 11

Inheritance example with custom classes:

<!DOCTYPE html>
<html>
<body>
 
<script>
class Student
{
  constructor()
  {
    this.college="NC College";
  }
}
class CollegeStudent extends Student {
  constructor(name,rollNo) {
   super();
    this.name=name;
    this.rollNo=rollNo;
  } 
}
var stu = new CollegeStudent("Navdeep",12);
document.writeln(stu.college+" "+stu.name+" "+stu.rollNo);
</script>
 
</body>
</html>

Output:

NC College Navdeep 12
Please Share