From here, refer to the below code. Here super()
is called to avoid duplicating the constructor parts' that are common between Rectangle
and Square
.
class Rectangle {
constructor(height, width) {
this.name = 'Rectangle';
this.height = height;
this.width = width;
}
sayName() {
console.log('Hi, I am a ', this.name + '.');
}
get area() {
return this.height * this.width;
}
set area(value) {
this._area = value;
}
}
class Square extends Rectangle {
constructor(length) {
this.height; // ReferenceError, super needs to be called first!
// Here, it calls the parent class's constructor with lengths
// provided for the Rectangle's width and height
super(length, length);
// Note: In derived classes, super() must be called before you
// can use 'this'. Leaving this out will cause a reference error.
this.name = 'Square';
}
}
Now, why calling this
before super()
will result in a ReferenceError
? Well, there is no straightforward answer to that question. However, the intuition is that this requirement ensures that a superclass constructor has had a chance to initialize itself before the allocated object is used. This means that if you write a base class, you don't have to worry about subclasses accidentally forgetting to call super()
but still invoking methods that assume that initialization has taken place.