SyntaxError: Unexpected '#' used outside of class body - JavaScript 编辑

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:106 次

字数:2691

最后编辑:7 年前

编辑次数:0 次

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文