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
Answers
In JavaScript, private class fields (denoted by the # symbol) cannot be accessed or enumerated outside of the class itself. They are intentionally designed to be inaccessible from outside the class for encapsulation and data privacy purposes.
However, it would be possible if you explicitly point to this fields.
It is impossible.
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.