为什么第一次在javascript中返回空原型对象? [英] Why is the class return empty prototype object first time in javascript?

查看:98
本文介绍了为什么第一次在javascript中返回空原型对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆