gpt4 book ai didi

javascript - 为什么js类不使用public和private关键字?

转载 作者:行者123 更新时间:2023-12-05 01:15:40 24 4
gpt4 key购买 nike

所以当他们创建 es6 类时,他们只是默认公开所有内容,这对我来说有点奇怪,但我还是同意了,因为我仍然使用旧的基于 es5 样式范围的类。

不管怎样,几年后,我们在类(class)中获得了私有(private)成员,这看起来很棒,但是你看一下语法:

somePublicVar = 10;
#somePrivateVar = 20;

如您所见,我们现在必须在私有(private)内容前加上井号/井号,这似乎是一个非常奇怪的选择,因为 JS 有 publicprivate 关键字,它们是保留供将来使用,所以现在我们要区分公共(public)和私有(private),为什么不现在就这样做。

public somePublicVar = 10;
private somePrivateVar = 20;

所以我确信这是有技术原因的,但我很难找到它,因为现在似乎是将这些 publicprivate 从保留到“使用中”,使其对给定成员的访问修饰符更加明确和明显。

最佳答案

官方FAQ回答:

Why aren't declarations private x?

This sort of declaration is what other languages use (notably Java), and implies that access would be done with this.x. Assuming that isn't the case (see above), in JavaScript this would silently create or access a public field, rather than throwing an error. This is a major potential source of bugs or invisibly making public fields which were intended to be private.

It also allows a symmetry between declaration and access, just as there is for public fields:

class A {
pub = 0;
#priv = 1;
m() {
return this.pub + this.#priv;
}
}

https://github.com/tc39/proposal-class-fields/blob/master/PRIVATE_SYNTAX_FAQ.md#why-arent-declarations-private-x

关于javascript - 为什么js类不使用public和private关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55394831/

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