0

With modern javascript we can have private members on classes

  class someClass {
    #privateField = 'foo'
    #privateMethod() { ... }
  }

  const instance = new someClass(); // #privateField and #privateMethod are not accessible on the instance
  someClass.#privateField; // SyntaxError: Private field '#priv' must be declared in an enclosing class

For some time we've been able to have fields with names that are not valid identifiers (e.g. contains spaces, symbols, start with a number, etc.) by using computed values e.g.

  class someClass {
    ["member name that would otherwise be invalid"](){ ... } 
  }

Is it possible to mix the 2 and have private members with computed names?

e.g.

  class someClass {
    ["#private Member with invalid name"]() { ... } // this is not actually private
    #["private Member with invalid name"]() { ... } // this is not valid syntax
  }

I am writing code that generates other code (yes, I am aware of injection risks. Rest assured that I will handle them appropriately). I can be reasonably sure that the members I need to create will not have names that are valid as identifiers, hence I need to use the computed property name syntax. But I also want them to be private members.

There are numerous workarounds I could use including using symbols, mangling or obfuscating the names, or even private-by-convention.

I am hoping for a solution that is more elegant than any of these.

DJL
  • 2,060
  • 3
  • 20
  • 39
  • 1
    "*For some time we've been able to have fields with names that are not valid identifiers*" - uh, you mean since ES1? – Bergi Apr 13 '22 at 12:50
  • 1
    No, a private field name must be an identifier – Bergi Apr 13 '22 at 12:53
  • 1
    https://stackoverflow.com/questions/61197325/js-dynamically-access-private-fields-properties-members – Pointy Apr 13 '22 at 12:54
  • @Pointy Clearly my ability to search for existing answers is not as good as I thought :( – DJL Apr 13 '22 at 13:05
  • I could swear I saw an explanation somewhere in the MDN docs too, but I couldn't find it. – Pointy Apr 13 '22 at 13:10

0 Answers0