JavaScript Class Inheritance


Class Inheritance

To make a class inherit from another, use the extends keyword.

A new class, formed through class inheritance, adopts all the methods of another class.

The super() method is used to talk about the parent class.

In the constructor method, when we use the super() method, it means we are invoking the constructor method of the parent. This allows us to use the properties and methods of the parent class.

Using inheritance in coding helps you reuse the features and actions of an already-made class when you're making a new class.


Getters and Setters

Classes also enable the use of getters and setters.

Using getters and setters for your properties can be wise, especially when you need to perform specific actions with the value before retrieving or setting them.

To include getters and setters in a class, utilize the get and set keywords.

Note:If the getter is a method, don't use parentheses when you're trying to obtain the property value.

The method for getting or setting a value cannot have the same name as the property, like in this situation with the carname.

The getter/setter method's name must be different from the property name, specifically in this instance, carname.

To employ asetter, follow the same format as when you assign a value to a property, but exclude parentheses:


Hoisting

Class declarations in JavaScript are not hoisted, unlike functions and other JavaScript declarations.

This implies that you need to state a class before putting it into action:

Note: Unlike variables, if you try to use functions or other declarations before they are actually declared, JavaScript won't throw an error. This is because JavaScript declarations are hoisted, meaning they are moved to the top by default.