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

SyntaxError: Unexpected '#' used outside of class body

· 52CE 我爱测

The JavaScript exception "Unexpected '#' used outside of class body" occurs when a hash ("#") is encountered in an unexpected context, most notably outside of a class declaration. Hashes are valid at the beginning of a file as a hashbang comment, or inside of a class as part of a

The JavaScript exception "Unexpected '#' used outside of class body" occurs when a hash ("#") is encountered in an unexpected context, most notably outside of a class declaration. Hashes are valid at the beginning of a file as a hashbang comment, or inside of a class as part of a private field. You may encounter this error if you forget the quotation marks when trying to access a DOM identifier as well.

Message

SyntaxError: Unexpected '#' used outside of class body.

Error type

SyntaxError

What went wrong?

We encountered a # somewhere unexpected. This may be due to code moving around and no longer being part of a class, a hashbang comment found on a line other than the first line of a file, or accidentally forgetting the quotation marks around a DOM identifier.

Examples

Missing quotation marks

For each case, there might be something slightly wrong. For example

document.querySelector(#some-element)

This can be fixed via

document.querySelector("#some-element");

Outside of a class

class ClassWithPrivateField {
  #privateField;

  constructor() {}
}

this.#privateField = 42;

This can be fixed by moving the private field back into the class

class ClassWithPrivateField {
  #privateField;

  constructor() {
    this.#privateField = 42;
  }
}

See also

  • SyntaxError

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

资料来源与适用范围

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

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

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