有了公共(public)领域,我可以这样做:
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) + "")
我可以将什么等价物用于私有(private)字段?
我只看到带有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)
还有很多其他的。为什么不呢?
最佳答案
There are no private computed property names:
#foo
is a private identifier, and#[foo]
is a syntax error.
Why doesn't this['#x']
access the private field named #x
, given that this.#x
does?
要解决这个问题,您需要使用 if/else 语句并以非动态方式设置每个语句:
class Smth {
#a = 0
#b = 0
constructor(value, isA) {
isA ? (this.#a = value) : (this.#b = value)
}
toString() {
return `(${this.#a}, ${this.#b})`
}
}
console.log(new Smth(1, true) + "")
console.log(new Smth(2, false) + "")
关于javascript - 在运行时选择私有(private)字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57661515/