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++.
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: