Constructors and class inheritance

Gaetano Violante
20-07-2017

In order to make the code more modular and keep features separated you can use an interesting feature coming with ES6, known in object oriented programming languages as class inheritance.

But, before looking at the code, would be nice to have a brief description about what we are going to build. Suppose having two different classes Polygon and Square. According to geometry, Squares belongs to Polygons set, therefore saying (and implement) Square class as a derived class of the Polygon class does make sense.

Let’s do it by code. We are creating two classes, one inheriting from the other, like here below:

class Polygon {
 constructor(area) {
 this.area = area;
 }
}

class Square extends Polygon {
   constructor(area) {
      super(area);
      this.side = Math.sqrt(area);
   }
}

All the following statements are true:

  • The class Polygon has a property named area whose value is set every time a Polygon object is created, this done by means of Polygon class constructor
  • The class Square inherits from the class Polygon. Also this class has a constructor, which calls the base class constructor by means of super keyword
  • The class Square has got a new property named side. This implementation makes sense, because every time we create a Square object, we are passing the area as constructor input parameter. This means that, according to geometry, we also know the square side value, which can be calculated as square root of its area. Note that the side property is not defined for Polygon class because not all the Polygons are regular (for irregular polygons side definition doesn’t make any sense)

Everything is now ready to instantiate the objects. You might be interested in how these objects are structured, using the browser console.log:


let p = new Polygon(50);
console.log(p);
let s = new Square(100);
console.log(s);

Just to finalize, classes inheritance is a powerful feature you can find in many programming languages and nowadays JavaScript also is moving into that direction. This helps developers to keep the code clean and well organized. I really invite you to comment hereby in case you have code improvements or any suggestions.

Thanks for reading!

Gaetano

LEAVE A REPLY

you might also like