Hsi*_*sao 2 javascript ecmascript-6
我在下面有一个代码,正如你在第一次看到console.log类的原型时那样,它返回空,但是这个类中的new对象实际上可以响应那些方法,然后我在原型中添加函数并带来新对象成功,怎么解释呢?
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())
Run Code Online (Sandbox Code Playgroud)
Polygon {}
27084
27084
Polygon { test: [Function] }
test
Run Code Online (Sandbox Code Playgroud)
怎么解释呢?
通过class语法创建的方法/属性是不可枚举的,并且您记录该值的环境似乎不显示不可枚举的属性.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'));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
647 次 |
| 最近记录: |