如何枚举私有 JavaScript Class 字段

How to Enumerate Private JavaScript Class Fields

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

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();

不可能。它们是私有字段,并且没有针对它们的枚举方法。只有 class 声明静态地知道声明了哪些。它们不是属性,甚至没有表示私有名称的语言值,你 cannot access them dynamically (like with bracket notation).

你会得到最好的是

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);
}

私有领域提案中有 an open issue 关于“私有领域迭代”,但是 TC39 成员的第一个评论之一是“私有字段不是属性。您无法通过设计反映它们。".

也许不是一个优雅的解决方案,但也许您可以修改您的结构来执行以下操作:

class Person {
  #properties = {
      isFoo: true,
      isBar: false
  };

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

  enumeratePrivateSelf() {
    // enumerate through private fields
    for (let key in this.#properties) {
      console.log(key)
      // (only public fields shown)
    }
  }
}