gpt4 book ai didi

javascript - 有没有一种简化方法来初始化多个私有(private)实例变量?

转载 作者:行者123 更新时间:2023-12-01 17:14:09 25 4
gpt4 key购买 nike

是否有一种简化方式来初始化多个私有(private)实例变量?

class Foo {
#bar
#bam
constructor(o) {
Object.assign(this, o) // not valid
}
}

const f = new Foo({ '#bar': 'this is bar', '#bam': 'this is bam' })

最佳答案

假设您的代码基于 Class field declarations for JavaScript proposal (具体来说,private fields):

There are no private computed property names: #foo is a private identifier, and #[foo] is a syntax error.

另见 private syntax FAQ :

Why doesn't this['#x'] access the private field named #x, given that this.#x does?

  1. This would complicate property access semantics.

  2. Dynamic access to private fields is contrary to the notion of 'private'. E.g. this is concerning:

class Dict extends null {
#data = something_secret;
add(key, value) {
this[key] = value;
}
get(key) {
return this[key];
}
}
(new Dict).get('#data'); // returns something_secret

But doesn't giving this.#x and this['#x'] different semantics break an invariant of current syntax?

Not exactly, but it is a concern. this.#x has never previously been legal syntax, so from one point of view there can be no invariant regarding it.

On the other hand, it might be surprising that they differ, and this is a downside of the current proposal.

您不能像使用普通属性那样动态访问私有(private)字段。据我所知,因此没有办法实现你想做的事情。

此外,外部代码知道并试图定义私有(private) 字段似乎很奇怪。也许您应该改用 get/set

关于javascript - 有没有一种简化方法来初始化多个私有(private)实例变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63702899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com