Javascript Class Extends example

JavaScript classes can be used as a model to instantiate a multitude of different objects.

The reserved word extends is used in JavaScript classes when a class inherits everything from a model class.

The new inherited class collects in the constructor the properties of the base class using the reserved word "super". It can also add new properties.

The methods of the new class are inherited directly and can be used with the word "this". You can also create new methods that cannot be used by the main class or model.

Explaining the example:

There is a model class called "House" with several properties reflected in the constructor function.

This class has a method that collects the area of any object that is an instance of this class.

A MiniHouse class is created that inherits from the House class. This class collects all the properties of the main class and adds a new property "depth".

The new inherited class has 3 methods:

  •  A validateMiniHouse method to validate a mini house using the getArea method of the main class.
  •  A getDimensions method to calculate the dimensions of the house.
  •  A showdata method to display results on the screen.
Comments

PHP Captcha


Interesting Articles