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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With