Inheritance
Inheritance lets you create type hierarchies and reuse code. A parent class and its subclasses share state and behavior.
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"}
- The
extendskeyword declaresGradStudentas a subclass ofStudent. - The
superkeyword calls the parent class’s constructor. - The
super()call in theGradStudentconstructor lets the parent class’s constructor setnameandemail. - If you omit the constructor in a subclass, JavaScript provides a default one that simply calls
super(...args). This differs from Java or C++, where you must explicitly define constructors.
Custom Error Objects
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);
}
}