The JavaScript inheritance is a mechanism that allows us to create new classes on the basis of already existing classes.
It provides flexibility to the child class to reuse the methods and variables of a parent class.
The JavaScript extends keyword is used to create a child class on the basis of a parent class.
It facilitates child class to acquire all the properties and behavior of its parent class.
Points to remember
- It maintains an IS-A relationship.
- The extends keyword is used in class expressions or class declarations.
- Using extends keyword, we can acquire all the properties and behavior of the inbuilt object as well as custom classes.
- We can also use a prototype-based approach to achieve inheritance.
JavaScript extends Example: inbuilt object
In this example, we extends Date object to display today's date.
Output:
Current date: 31-8-2018
Let's see one more example to display the year value from the given date.
Output:
Year value: 1947
JavaScript extends Example: Custom class
In this example, we declare sub-class that extends the properties of its parent class.
Output:
Honda Shine 70000
JavaScript extends Example: a Prototype-based approach
Here, we perform prototype-based inheritance. In this approach, there is no need to use class and extends keywords.
Output:
Honda Shine 70000
No comments:
Post a Comment