为什么第一次在javascript中返回空原型对象? [英] Why is the class return empty prototype object first time in javascript?
问题描述
codebase
class多边形{
构造函数(height,width){
this.height = height;
this.width = width;
}
get area(){
return this.calcArea()
}
calcArea(){
return this.height * this.width;
}
}
console.log(Polygon.prototype)
多边形=新的多边形(222,122)
console.log .area)
console.log(polygon.calcArea())
Polygon.prototype.test = function(){returntest}
console.log(Polygon。原型)
console.log(polygon.test())
输出
多边形{}
27084
27084
多边形{test:[Function]}
test
如何解释?
通过类
语法创建的方法/属性是 -enumerable ,并且似乎记录值的环境不显示不可枚举的属性。 console.log
不是标准化的,所以不同的环境中的输出不一样。
通过
class多边形{constructor(height,width){this.height = height; this.width = width; } get area(){return this.calcArea()} calcArea(){return this.height * this.width; }} Polygon.prototype.test = function(){returntest} //注意`enumerable`console.log(Object.getOwnPropertyDescriptor(Polygon.prototype,'calcArea'))的不同值); console.log(Object .getOwnPropertyDescriptor(Polygon.prototype,'test'));
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, then I add function in prototype and bring new object successful, how can explain it?
codebase
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())
output
Polygon {}
27084
27084
Polygon { test: [Function] }
test
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'));
这篇关于为什么第一次在javascript中返回空原型对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!