Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interpret `subclass.__proto__ === parentClass` in JavaScript inheritance?

Tags:

javascript

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.

like image 759
desen zhao Avatar asked Oct 30 '25 13:10

desen zhao


1 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:

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.

like image 105
Nick Parsons Avatar answered Nov 02 '25 03:11

Nick Parsons