Differences in using super() when extending a class

Viewed 75

I'm learning about creating a new class, extending it and subclassing. I don't understand the following:

  • Why in extending the class in example #2 both the constructor() and the super() use length as an argument?
  • If super() in example #2 is supposed to access the parent class Polygon, shouldn't it use as arguments height and width to access them in the Polygon class instead of length (like it does in example #4)? If not, why?

Source code is: https://googlechrome.github.io/samples/classes-es6/index.html

// Example 1: Creating a new class (declaration-form)
// ===============================================================

class Polygon {
  constructor(height, width) {
    this.name = 'Polygon';
    this.height = height;
    this.width = width;
  }
  sayName() {
    console.log('Hi, I am a ', this.name + '.');
  }

  sayHistory() {
    console.log('"Polygon" is derived from the Greek polus (many) ' +
      'and gonia (angle).');
  }
}


// Example 2: Extending an existing class
// ===============================================================

class Square extends Polygon {
  constructor(length) {
    super(length, length);
    this.name = 'Square';
  }
  get area() {
    return this.height * this.width;
  }
  set area(value) {
    this.area = value;
  }
}

let s = new Square(5);

s.sayName();
console.log('The area of this square is ' + s.area);

// Example 4: Subclassing methods of a parent class
// ===============================================================

class Rectangle extends Polygon {
  constructor(height, width) {
    super(height, width);
    this.name = 'Rectangle';
  }
  sayName() {
    console.log('Sup! My name is ', this.name + '.');
    super.sayHistory();
  }
}

let r = new Rectangle(50, 60);
r.sayName();
1 Answers

It makes sense that a square takes only one argument - the length of one of its sides. But if the Square is a type of Polygon, Polygons here require two arguments, a height and a width.

If one instantiates a Square, that square needs to call super to run the Polygon constructor, which expects two arguments, height and width. In the Square constructor, those are the same - the length variable, hence the call

super(length, length);

Example 4 is different because it's a Rectangle, not a Square. Rectangles accept two arguments, a height and a width, just like Polygons, so both the Rectangle constructor and the Polygon constructor are called with (height, width), and the super call reflects that:

super(height, width);
Related