I try to declare private Symbol property in ES6+ class, below’s approach are all wrong.
class MyClass {
#[Symbol.for('my-symbol-prop1')] = 'my-symbol-prop1'; // SyntaxError
[#Symbol.for('my-symbol-prop1')] = 'my-symbol-prop1'; // SyntaxError
}
My question: Is there any way to declare a true private Symbol property, just using hash notation like #myPrivateSymbolfield
, don’t using WeakMap
or enclosure approach
2
Answers
Currently in JavaScript, there isn’t a direct way to create private Symbol properties using the private field syntax (
#
). The private fields feature and Symbol properties serve different purposes. Having said that, you can easily do a workaround for the same i.e. use astatic private
field to store the symbol. Something like below:This is not possible. Symbol-keyed properties are just regular object properties (just with symbols instead of string names), not private fields. If you want a field with a private name, do not use symbols.