Why is the class return empty prototype object first time in javascript?

后端 未结 1 712
暖寄归人
暖寄归人 2021-01-21 16:20

I have a code in below, as you see when console.log the prototype of the class first time, it return empty, but the object new from this class actually can response those method

相关标签:
1条回答
  • 2021-01-21 17:01

    how can explain it?

    Methods/properties created through the class syntax are non-enumerable and it seems that the environment you log the value in doesn't show non-enumerable properties. console.log is not standardized, so different outputs in different environments have to be expected.

    Creating a property through assignment always creates an enumerable property.

    class Polygon {
      constructor(height, width) {
        this.height = height;
        this.width = width;
      }
    
      get area() {
        return this.calcArea()
      }
    
      calcArea() {
        return this.height * this.width;
      }
    }
    Polygon.prototype.test = function(){ return "test"}
    
    // Note the different values for `enumerable`
    console.log(Object.getOwnPropertyDescriptor(Polygon.prototype, 'calcArea'));
    console.log(Object.getOwnPropertyDescriptor(Polygon.prototype, 'test'));

    0 讨论(0)
提交回复
热议问题