Inheritance is a powerful tool for creating type hierarchies and reusing code, allowing sharing between parent and subclasses.
JavaScript now supports inheritance with syntax similar to 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); // {"name":"John Doe","email":"john@email.com"}
console.log(jane); // {"name":"Jane Doe","email":"jane@email.com","advisor":"Prof. Smith"}
extends
keyword declares GradStudent
as a subclass of Student
.super
keyword is used to invoke the parent class’s constructor.super()
call within the GradStudent
constructor delegates the initialization of name
and email
to the parent class’s constructor.super()
call to the parent constructor. This is not the case for non default constructors in Java or C++.A good example of inheritance in JavaScript is creating custom error objects. JavaScript provides built-in error objects like Error
, SyntaxError
, ReferenceError
, etc. You can also create custom error objects by extending the built-in Error
class:
class CustomError extends Error {
constructor(message) {
super(message);
this.name = 'CustomError';
}
}
function riskyOperation() {
throw new CustomError('Something went wrong in the risky operation');
}
try {
riskyOperation();
} catch (error) {
if (error instanceof CustomError) {
console.error('A custom error occurred:', error.message);
} else {
console.error('An unexpected error occurred:', error);
}
}