语法错误:对未声明的私有字段或方法 #x 的引用

当使用 私有名称 但此私有名称未在类范围内声明时,会发生 JavaScript 异常 "对未声明的私有字段或方法 #x 的引用"。

¥The JavaScript exception "reference to undeclared private field or method #x" occurs when a private name is used, but this private name is not declared in the class scope.

信息

¥Message

SyntaxError: Private field '#x' must be declared in an enclosing class (V8-based)
SyntaxError: reference to undeclared private field or method #x (Firefox)
SyntaxError: Cannot reference undeclared private names: "#x" (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

与普通字符串或符号属性不同,如果属性不存在,则返回 undefined,而私有名称非常严格,只有在实际存在时才能合法访问。访问未声明的私有名称将导致语法错误,而访问已声明但对象上不存在的私有名称将导致 类型错误

¥Unlike normal string or symbol properties, which return undefined if the property does not exist, private names are very strict and can only be legally accessed if they actually exist. Accessing an undeclared private name will result in a syntax error, while accessing a private name that is declared but doesn't exist on the object will result in a type error.

示例

¥Examples

未声明的私有字段

¥Undeclared private field

你无法访问未在类范围内声明的私有字段。

¥You cannot access a private field that is not declared in the class scope.

js
class MyClass {
  doSomething() {
    console.log(this.#x);
  }
}

如果使用 in 运算符对未声明的私有字段执行检查,则会出现相同的错误。

¥The same error occurs if you use the in operator to perform a check on an undeclared private field.

js
class MyClass {
  doSomething() {
    console.log(#x in this);
  }
}

这些代码可能是错误的,因为如果未在类范围内声明 #x,则 this 上不可能存在 #x。请注意,你不能动态地将私有属性添加到不相关的对象。你应该删除此代码或在类范围内声明私有字段。

¥These code are probably mistakes because it's impossible for #x to exist on this if it's not declared in the class scope. Note that you cannot dynamically add private properties to unrelated objects. You should either remove this code or declare the private field in the class scope.

js
class MyClass {
  #x = 0;
  doSomething() {
    console.log(this.#x);
  }
}

也可以看看

¥See also