skip to Main Content

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


  1. 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 a static private field to store the symbol. Something like below:

    class MyClass {
      [Symbol.for('my-symbol-prop')] = 'symbol';
      
      // Private Symbol wokraround using private field
      static #privateSymbol = Symbol('privateSymbol Desc');
      
      constructor() {
        /* The Symbol itself can be accessed via the getter
        but the property using this Symbol is still private */
    
        this[MyClass.#privateSymbol] = 'private symbol value';
      }
      
      get privateSymbolValue() {
        return this[MyClass.#privateSymbol];
      }
    }
    // Usage
    const myClass1 = new MyClass();
    const myClass2 = new MyClass();
    console.log(myClass1.privateSymbolValue);
    console.log(myClass2.privateSymbolValue);
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search