【问题标题】:Why is jshint throwing an error when i declare a class field?当我声明一个类字段时,为什么 jshint 会抛出错误?
【发布时间】:2021-01-09 11:10:26
【问题描述】:

应用中有一个App 类:

  class App {
      static cart;
      static init() {
        const shop = new Shop();
        shop.render();
        this.cart = shop.cart;
      }
    }

我使用VSCode 作为 IDE,jshint 作为代码质量工具。
static cart; 声明为App 类字段会导致Problems panel 中出现下一条错误消息:

(property) App.cart: any
Class properties must be methods. Expected '(' but instead saw ';'. (E054)jshint(E054)

我试图用谷歌搜索这个问题,但失败了。
你能告诉我,我做错了什么吗?
我是 JS 新手,所以我的代码中可能存在语法错误?

【问题讨论】:

  • 这是一个实验性功能,它还不是语言的一部分,参见例如developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。我不知道怎么做,但你可能需要一些配置来告诉 JSHint 你正在使用非标准语言功能。
  • ……甚至更好,只是不要在此处使用该语言功能。没有理由让 App 成为仅具有静态属性的 class。请改用对象文字。甚至是普通的let cart; function init() { … }

标签: javascript jshint


【解决方案1】:

我不清楚你的代码应该做什么(例如,我不知道Shop 是/做什么),但我可以告诉你类字段定义are allowed 并且不再是实验性的@ 987654322@.

我认为这是jshint(撰写本文时为v2.13.4)当前版本中的错误/限制,因为它尚未识别class fields。请参阅跟踪问题的https://github.com/jshint/jshint/issues/3139

不幸的是,对于这个项目,JSHint 近年来很难跟上其他工具的步伐。正如一位维护者所描述的here,这至少部分是由于其聪明而幽默但令人惊讶的问题许可协议。

另见:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-01
    • 2017-12-12
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多