In JavaScript, is there a way to enumerate all private properties of an object?

77 Views Asked by At

In the following code:

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

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

const foo = new Foo();

foo.tellYourself();

Only this is printed:

OK the values are {"c":3.14}

Is there a way to print out all properties automatically, including the private ones?

(meaning if there are 25 private variables, print all of them out automatically, instead of specifying them one by one?).

2

There are 2 best solutions below

3
Roman Lytvynov On

It is impossible.

The only way to access a private property is via dot notation, and you can only do so within the class that defines the private property.

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

So I can suggest you to redesign your solution according to your goal.

2
Alexander Nenashev On

Just for fun, you can extract private props from the class definition:

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

  tellYourself() {
    const props = Foo.toString().match(/(?<=^\s*#)[^ =;]+/gm);
    const priv = eval(`({${props.map(prop => `'#${prop}': this.#${prop}`).join(',')}})`);
    
    console.log("OK the values are", {...this, ...priv});
  }
}

const foo = new Foo();

foo.tellYourself();