Inheritance

JavaScript now supports inheritance with a syntax that is very similar to that in Java/C++.

class Student {
  constructor(name, email) {
    this.name = name;
    this.email = email;
  }
}

class GradStudent extends Student {
  constructor(name, email, advisor) {
    super(name, email);
    this.advisor = advisor;
  }
}

const john = new Student ("John Doe", "john@email.com");
const jane = new GradStudent ("Jane Doe", "jane@email.com", "Prof. Smith");

console.log(john instanceof Student);
console.log(jane instanceof Student);
console.log(john instanceof GradStudent);
console.log(jane instanceof GradStudent);

console.log(john);
console.log(jane);
  • Notice the use of extends keyword to declare GradStudent is a subclass of Student.
  • Also note the use of the keyword super to invoke the constructor of the parent class.
  • The super(..) delegates to the parent class’s constructor for its initialization work.
  • Unlike in Java/C++, constructors are also inherited in JavaScript. You don't need to explicitly define one if all it does is a super(..) call to the parent constructor.

Inheritance is a powerful tool for creating type hierarchies and reusing code (sharing between parent and subclasses).