javascriptprivateprivate-membersclass-fields

js dynamically access private fields (properties/members)


I'm trying out the new class private member feature 🎉 However, I've quickly run into a problem: How does one dynamically access them?

I expected it to follow pre-existing syntax of either

constructor(prop, val) {
  this[`#${prop}`] = val; // undefined
}

or

constructor(prop, val) {
  this.#[prop] = val; // syntax error
}

However, both of the above fail.


Solution

  • I dont think you can access private fields dynamically. The proposal says:

    There are no private computed property names: #foo is a private identifier, and #[foo] is a syntax error.