【发布时间】: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,谢谢你的帮助。