语法错误:在类主体之外使用了意外的 ''

当在意外上下文中遇到哈希 ("")(最明显的是 在类声明之外)时,就会发生 JavaScript 异常 "在类主体之外使用了意外的 ''"。哈希值在文件开头作为 话题评论 有效,或者在类内部作为私有字段的一部分有效。如果你在尝试访问 DOM 标识符时忘记了引号,则可能会遇到此错误。

¥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?

我们在意想不到的地方遇到了 #。这可能是由于代码移动并且不再是类的一部分、在文件第一行以外的行上发现了 hashbang 注释,或者意外地忘记了 DOM 标识符周围的引号。

¥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

js
document.querySelector(#some-element)

这可以通过修复

¥This can be fixed via

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

课堂之外

¥Outside of a class

js
class ClassWithPrivateField {
  #privateField;

  constructor() {}
}

this.#privateField = 42;

这可以通过将私有字段移回类中来解决

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

js
class ClassWithPrivateField {
  #privateField;

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

也可以看看

¥See also