【发布时间】:2019-12-30 20:35:34
【问题描述】:
使用公共字段我可以这样做:
class Smth {
a = 0
b = 0
constructor(value, isA) {
this[isA ? 'a' : 'b'] = value
}
toString() {
return `(${this.a}, ${this.b})`
}
}
console.log(new Smth(1, true) + "")
console.log(new Smth(2, false) + "")
我可以为私有字段使用什么等价物?
我只看到eval 的解决方案:
class Smth {
#a = 0
#b = 0
constructor(value, isA) {
eval(`this.#${isA ? 'a' : 'b'} = value`)
}
toString() {
return `(${this.#a}, ${this.#b})`
}
}
console.log(new Smth(1, true) + "")
console.log(new Smth(2, false) + "")
或完全分支到if-else的解决方案:
class Smth {
#a = 0
#b = 0
constructor(value, isA) {
if (isA) {
this.#a = value
} else {
this.#b = value
}
}
toString() {
return `(${this.#a}, ${this.#b})`
}
}
console.log(new Smth(1, true) + "")
console.log(new Smth(2, false) + "")
这两种解决方案都不适合我。
如果没有这样的方法,我想知道为什么。
很明显 this['#x'] 完全是另一回事。但是有很多方法可以用其他语法表达所需的东西,例如:
this.#[true ? 'x' : 'y']
this[true ? #x : #y]
this.#[true ? #x : #y]
this.#(true ? ##x : ##y)
还有很多其他的。为什么不呢?
【问题讨论】:
-
来自提案:没有私有计算属性名称:
#foo是私有标识符,#[foo]是语法错误See。还有更多信息:github.com/tc39/proposal-class-fields/blob/master/…
标签: javascript private