class Polygon {
constructor() {
this.name = "Polygon";
}
}
class Square extends Polygon {
constructor() {
super();
}
}
console.log(Square.__proto__ === Polygon); // true why?
console.log(Square.prototype.__proto__ === Polygon.prototype); // true
I can understand the second print statement being true, but I don't understand the first print statement being true.
It's so static fields/accessors/methods can be looked up on the parent class if it's not found on the child, for example:
class Polygon {
constructor() {
this.name = "Polygon";
}
static staticPolygonMethod() {
return "staticPolygon";
}
}
class Square extends Polygon {
constructor() {
super();
}
}
console.log(Square.staticPolygonMethod()); // staticPolygon
As static fields/accessors/methods are added to the class itself, the staticPolygonMethod is set on Polygon class/function itself.
In this example above, staticPolygonMethod is not found on the Square class/function, so its [[Prototype]] is checked for the property, which is set to Polygon, as you've seen with the Square.__proto__ === Polygon check. Because staticPolygonMethod exists on the Polygon class/function, it can now be found correctly in Square's prototype chain and thus used as expected on Square.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With