class A {
#a = 1;
static #a = 2;
}
结果是Uncaught SyntaxError: redeclaration of private name #a
在火狐Uncaught SyntaxError: Identifier '#a' has already been declared
在 Chrome 尽管
class A {
a = 1;
static a = 2;
}
在 Firefox 和 Chrome 中都有效AFAIK 实例字段将安装在类实例上,而静态字段将安装在类对象本身上。他们并不冲突。为什么以前的代码无效?
最佳答案
Instance fields will be installed on the class instance while static fields will be installed on the class object itself. They are not conflicted.
它们是,因为在表达式
x.#a
引擎不知道 x
是类对象或类实例。 #a
的含义 token 应该是静态的并且不依赖于对象,它需要引用一个或另一个,但不能同时引用两者。与由标识符的字符串值标识的普通字符串键属性不同(
.a
与 .a
相同,无论上下文如何),私有(private)字段具有使用其声明创建的标识(与符号不同)。只有一个#a
可以存在于 class
定义,并且在不同的类中相同 #a
语法将引用不同的字段。
关于javascript - JavaScript 中的私有(private)类字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67920793/