jac*_*cob 13 javascript private private-members class-fields
我正在尝试新的类私有成员功能 但是,我很快遇到了一个问题:如何动态访问它们?
我希望它遵循预先存在的语法
constructor(prop, val) {
this[`#${prop}`] = val; // undefined
}
Run Code Online (Sandbox Code Playgroud)
或者
constructor(prop, val) {
this.#[prop] = val; // syntax error
}
Run Code Online (Sandbox Code Playgroud)
然而,以上两种方法都失败了。
小智 9
另一种选择是为您想要动态访问的密钥提供一个私有对象:
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
Run Code Online (Sandbox Code Playgroud)
小智 5
如果你真的想这么做的话。
eval(`this.#${propertyName}`)
Run Code Online (Sandbox Code Playgroud)
但这只是打开了一个非常丑陋的蠕虫罐头。
| 归档时间: |
|
| 查看次数: |
2024 次 |
| 最近记录: |