简体   繁体   English

关于 JavaScript 对象的方法不可枚举的困惑

[英]Confusion about JavaScript Object's method being non-enumerable

class RandomObject {
  constructor() {
    this.method1 = function() {}
  }

  method2() {
    // only this is non enumerable
  }

  method3 = function() {}
}

const object = new RandomObject()

for (const prop in object) {
  console.log(prop) // 'method1', 'method2'
}

I found that only method1 and method2 are printed out in the for...in loop, meaning they are enumerable.我发现在for...in循环中只有method1method2被打印出来,这意味着它们是可枚举的。 However method2 doesn't show up in the loop, meaning it is non-enumerable.但是method2没有出现在循环中,这意味着它是不可枚举的。 I wonder what caused the differences here?我想知道是什么导致了这里的差异? Why is that only method2 is non-enumerable in this case?为什么在这种情况下只有method2是不可枚举的?

Also, I found that if I define the method directly in the object literal, then it is enumerable again:另外,我发现如果我直接在 object 文字中定义方法,那么它又是可枚举的:

const object2 = {
  method2() {
    // Now this is enumerable
  }
}

Class prototype methods are non-enumerable - that's just the way the syntax was designed: Class 原型方法是不可枚举的——这正是语法的设计方式:

 class X { method() { } } console.log(Object.getOwnPropertyDescriptor(X.prototype, 'method').enumerable);

See CreateMethodProperty in ClassDefinitionEvaluation , which requires that class methods be non-enumerable.请参阅ClassDefinitionEvaluation中的CreateMethodProperty ,它要求 class 方法是不可枚举的。

In contrast, class field syntax - that is, someProperty = someExpression directly inside the class body - is syntax sugar for running this.someProperty = someExpression inside the constructor.相比之下,class 字段语法——即直接在 class 主体内的someProperty = someExpression是在构造函数内运行this.someProperty = someExpression的语法糖。 Ordinary assignment to a property that doesn't exist on the object yet results in the property being enumerable.对 object 上不存在的属性的普通分配会导致该属性是可枚举的。

class RandomObject {
  method3 = function() {}
}

is equivalent to相当于

class RandomObject {
  constructor() {
    this.method3 = function() {}
  }
}

With methods on ordinary objects, see PropertyDefinitionEvaluation , which describes how properties (including methods) get created in object literals.对于普通对象的方法,请参阅PropertyDefinitionEvaluation ,它描述了如何在 object 文字中创建属性(包括方法)。 It'll carry out它会执行

Return?返回? MethodDefinitionEvaluation of MethodDefinition with arguments object and enumerable. MethodDefinition 使用 arguments object 和可枚举的 MethodDefinition 评估。

where enumerable has been set to true with ObjectLiterals .其中enumerable已使用ObjectLiterals设置为true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM