在JavaScript中,有没有办法枚举对象的所有私有属性?

问题描述 投票:0回答:2

在以下代码中:

class Foo {
  #a;
  #b = 123;
  c = 3.14;

  tellYourself() {
    console.log("OK the values are", JSON.stringify(this));
  }
}

const foo = new Foo();

foo.tellYourself();

仅打印此:

OK the values are {"c":3.14}

有没有办法自动打印出所有属性,包括私有属性?

(意思是如果有25个私有变量,自动将它们全部打印出来,而不是一一指定它们?)。

javascript private-members
2个回答
2
投票

这是不可能的。

访问私有属性的唯一方法是通过点表示法,并且只能在定义私有属性的类中执行此操作。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties

所以我可以建议您根据您的目标重新设计您的解决方案。


-1
投票

在 JavaScript 中,私有类字段(用 # 符号表示)无法在类本身之外访问或枚举。出于封装和数据隐私的目的,它们被有意设计为无法从类外部访问。

但是,如果您明确指向此字段,则是可能的。

class Foo {
  #a;
  #b = 123;
  c = 3.14;

  getAllProperties() {
    return {
      c: this.c,
      '#a': this.#a,
      '#b': this.#b
    };
  }

  tellYourself() {
    console.log("All properties:", this.getAllProperties());
  }
}

const foo = new Foo();

foo.tellYourself();

© www.soinside.com 2019 - 2024. All rights reserved.