Inheritance

JavaScript now supports inheritance with a syntax 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);     // true
console.log(jane instanceof Student);     // true
console.log(john instanceof GradStudent); // false
console.log(jane instanceof GradStudent); // true

console.log(john);
console.log(jane);
  • Notice the extends keyword to declare GradStudent is a subclass of Student.
  • Also note the use of the keyword super to invoke the parent class's constructor.
  • The super() call inside the GradStudent constructor delegates initialization of name and email to the parent class's constructor.
  • Unlike in Java/C++, constructors are also inherited in JavaScript. Therefore, 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).