Introduction to JavaScript Class Inheritance
Class inheritance is a fundamental concept in object-oriented programming that allows one class to inherit properties and methods from another class. In JavaScript, class inheritance is implemented using the extends
keyword, providing a way to create a class as a derived class that inherits from a base class.
For more information about the basic syntax, see JavaScript: Classes and Basic Syntax.
Creating a Derived Class
To create a class that inherits from another, we use the extends
keyword:
In this example, Circle
extends Shape
, meaning it inherits Shape
's properties and methods, and at the same time providing methods of it's own.
Overriding Methods
Derived classes can override methods of their base classes to provide behavior specific to the subclass.
Here, Circle
overrides the print
method to reflect its specific type.
Accessing Parent Constructor: super
keyword
When a class extends another class, the constructor function of the derived class needs to call the parent's constructor using super()
before it can use this
. Here’s how super is used in constructors to ensure the parent class is initialized:
Summary
JavaScript class inheritance is a powerful feature that allows for the creation of a more manageable and hierarchical object model. By understanding and using inheritance effectively, you can write more organized and modular JavaScript code. Inheritance not only promotes code reuse but also helps in creating an intuitive relationship between components in your application.
Practice Your Knowledge
Quiz Time: Test Your Skills!
Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.