【问题标题】:Why is the class return empty prototype object first time in javascript?为什么类在javascript中第一次返回空原型对象?
【发布时间】:2017-05-25 17:19:40
【问题描述】:

我在下面有一个代码,正如你第一次看到console.log类的原型时,它返回空,但是这个类的新对象实际上可以响应那些方法,然后我在原型中添加函数并带来新对象成功,如何解释?

代码库

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  
  get area() {
    return this.calcArea()
  }

  calcArea() {
    return this.height * this.width;
  }
}

console.log(Polygon.prototype)

polygon = new Polygon(222,122)
console.log(polygon.area)
console.log(polygon.calcArea())

Polygon.prototype.test = function(){ return "test"}
console.log(Polygon.prototype)
console.log(polygon.test())

输出

Polygon {}
27084
27084
Polygon { test: [Function] }
test

【问题讨论】:

  • 你在什么浏览器中测试这个?在 Chrome 的控制台中,我看到Object {constructor: function, calcArea: function} 是第一个日志条目。
  • @apsillers,好像是导致不同环境的console.log,谢谢你的帮助。

标签: javascript ecmascript-6


【解决方案1】:

怎么解释?

通过class 语法创建的方法/属性是non-enumerable,您记录值的环境似乎没有显示不可枚举的属性。 console.log 没有标准化,所以不同环境下的输出是不同的。

通过赋值创建一个属性总是会创建一个可枚举的属性。

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'));

【讨论】:

  • 谢谢,这个类好像有原型但是控制台日志没有显示,我的高级目标和问题我想要的是stackoverflow.com/questions/44186968/…,如果你有兴趣,欢迎尝试解决它跨度>
猜你喜欢
  • 2021-04-22
  • 1970-01-01
  • 2020-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-22
  • 2015-01-18
  • 2018-02-23
相关资源
最近更新 更多