Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 880
Jakob Jingleheimer Avatar asked Feb 18 '26 22:02

Jakob Jingleheimer


1 Answers

Another option is to have a private object for the keys you want to access dynamically:

class privateTest {
  #pvt = {}

  constructor(privateKey, privateVal) {
    this.#pvt[privateKey] = privateVal;
  }

  getPrivate(privateKey) {
    return this.#pvt[privateKey];
  }

}

const test = new privateTest('hello', 'world');
console.log(test.getPrivate('hello')) // world
like image 95
adriancg Avatar answered Feb 20 '26 11:02

adriancg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!