I have the following code:
class Polygon {
constructor() {
this.name = "Polygon";
}
}
class Rectangle {
constructor() {
this.name = "Rectangle";
}
}
class Square extends Polygon {
constructor() {
super();
}
}
Object.setPrototypeOf(Square, Rectangle);
const instance = new Square();
console.log(instance.name); // Rectangle
My understanding is:
Instance__proto__
: Points to Square.prototype to inherit instance methods.Subclass.__proto__
: Points to Rectangle to inherit static methods and properties.Square.prototype.__proto__
: Points to Polygon.prototype to inherit the parent class’s instance methods.
My Question:
In the code above, after using Object.setPrototypeOf(Square, Rectangle)
, the Square._proto_
is now pointing to Rectangle and not Polygon for all static properties. And for inheriting all the other methods Square.prototype._proto_
points to Polygon.prototype
. So, then I expect super()
in Square to invoke Polygon’s constructor, since Square extends Polygon. However, it seems like super() is invoking Rectangle’s constructor instead. I’m confused now, what all gets changed when Object.setPrototypeOf(Square, Rectangle)
is run, seems like there is a gap in my understanding.