skip to Main Content
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


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

    Login or Signup to reply.
  2. The extends keyword sets up two prototype chains:

    • Sets parentClass.prototype object as the prototype of the childClass.prototype

    • Sets parentClass constructor as the prototype of the childClass constructor

    In your case, the two prototype chains that extends keyword forms are as shown below:

    Square.prototype ---> Polygon.prototype ---> Object.prototype
    
    Square ---> Polygon ---> Function.prototype ---> Object.prototype
    

    The second point is related to your question and it is done to allow the lookup of static properties on the parent constructor.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search