Home > OS >  Why does super function calls itself constructor?
Why does super function calls itself constructor?

Time:10-01

I found an example from MDN about super. I learned that super function calls parent's constructor so that the subclass can inherit all the properties/methods from it. However, in the example from MDn, it calls the subclass's constructor.

<script>
class Rectangle {
  constructor(height, width) {
    this.name = 'Rectangle';
    this.height = height;
    this.width = width;
  }
}
class Square extends Rectangle {
  constructor(length) {
    super(length, length);
    this.name = 'Square';
  }
}
let a = new Square(4);
console.log(JSON.stringify(a));
console.log(a.height);
</script>

So we have a Square constructor which extends from Rectangle. My confusion is at the super function which has two arguments from Square but Square is the subclass of Rectangle. Wouldn't it make sense to call super within Square and pass height and width from Rectangle to it so that Square can inherit the height and width from Rectangle since Square is extending Rectangle?

CodePudding user response:

Inheritance happens automatically, you don't need to call super() for this.

super() is used to run the parent class's constructor. When you call new Square(4), this calls the Square constructor automatically with length = 4. But the Rectangle constructor requires two parameters, not the same parameters as the Square constructor. The design of Square is that it's a rectangle whose height and width are the same, so the Square constructor can pass this length parameter to Rectangle to express this idea.

We can't go the other way, because a class can have many different subclasses, and they can each have different relationships with it. There's no way for the superclass to call all possible subclass constructors, since subclasses can be added arbitrarily.

CodePudding user response:

in the example from MDN, it calls the subclass's constructor.

No it doesn't.

Wouldn't it make sense to call super within Square […] so that Square can inherit the height and width from Rectangle since Square is extending Rectangle?

That's exactly what's happening.

… and pass height and width from Rectangle to it

small clarification: it's passing a value (the square side length) as height and width to Rectangle.

The new Square construction calls the new Rectangle construction.

  • Related