如何枚举私有JavaScript类字段

Ant*_*ris 3 javascript javascript-objects

我们如何枚举私有类字段?

class Person {
  #isFoo = true;
  #isBar = false;

  constructor(first, last) {
    this.firstName = first;
    this.lastName = last;
  }

  enumerateSelf() {
    console.log(this);
    // (pub/priv fields shown)

    // enumerate through instance fields
    for (let key in this) {
      console.log(key)
      // (only public fields shown)
    }

    // How do we enumerate/loop through private fields too?
  }
}

new Person('J', 'Doe').enumerateSelf();
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 5

这是不可能的。它们是私有字段,没有枚举方法。只有类声明才能静态知道哪些声明了。它们不是属性,甚至没有代表私有名称的语言值,您无法动态访问它们(如带括号的符号)。

最好的是

enumerateSelf() {
    console.log(this);
    for (let key in this) {
        console.log("public", key, this[key]);
    }
    console.log("private isFoo", this.#isFoo);
    console.log("private isBar", this.#isBar);
}
Run Code Online (Sandbox Code Playgroud)

有一个开放的问题,在私人领域的提案关于“ 私人领域迭代 ”,然而由TC39成员国第一个评论“ 私人领域都没有的特性。你不能在设计上反映他们。 ”。

  • 希望只是暂时的,让我回顾一下 ECMA 规范并可能提出更改建议。 (2认同)