大网数据广告活动
Web 标准与前端开发

SyntaxError: reference to undeclared private field or method #x

· 52CE 我爱测

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.

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?

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.

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

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

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

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 elements to unrelated objects. You should either remove this code or declare the private field in the class scope.

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

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。