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.
2
Answers
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:As static fields/accessors/methods are added to the class itself, the
staticPolygonMethod
is set onPolygon
class/function itself.In this example above,
staticPolygonMethod
is not found on theSquare
class/function, so its[[Prototype]]
is checked for the property, which is set toPolygon
, as you’ve seen with theSquare.__proto__ === Polygon
check. BecausestaticPolygonMethod
exists on thePolygon
class/function, it can now be found correctly inSquare
‘s prototype chain and thus used as expected onSquare
.The
extends
keyword sets up two prototype chains:Sets
parentClass.prototype
object as the prototype of thechildClass.prototype
Sets
parentClass constructor
as the prototype of thechildClass constructor
In your case, the two prototype chains that
extends
keyword forms are as shown below:The second point is related to your question and it is done to allow the lookup of static properties on the parent constructor.