js动态访问私有字段(属性/成员)

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)


Bar*_*mar 6

我不认为你可以动态访问私有字段。该提案称:

没有私有计算属性名称:#foo是私有标识符,并且#[foo]是语法错误。


小智 5

如果你真的想这么做的话。

eval(`this.#${propertyName}`)
Run Code Online (Sandbox Code Playgroud)

但这只是打开了一个非常丑陋的蠕虫罐头。

  • 因此,为了实现这一目标,你必须转向黑暗面。 (3认同)