简体   繁体   English

类声明ECMAScript 6后分号的ESLint错误

[英]ESLint error on semicolon after class declaration ECMAScript 6

I have the following code: 我有以下代码:

class Car() {

    constructor() {
        // ...
    }

    withSemi() {
        // ...
    };  // ESLint does not complain here

    withoutSemi() {
       // ...
    }  // ESLint does not complain here

};  // ESLint will complain about this semicolon (no-extra-semi)

Can someone explain how the automatic semicolon insertion will work in ES6 in regards to classes and why ESLint has this behaviour? 有人可以解释自动分号插入在ES6中如何在类中运行以及ESLint为什么会出现这种行为?

According to the ECMAScript 2015 class specification , a semicolon is a valid ClassElement , so it can exist within a ClassBody . 根据ECMAScript 2015 class规范 ,分号是有效的ClassElement ,因此它可以存在于ClassBody

However, its semantics treat it as having no behavior whatsoever (for example, see NonConstructorMethodDefinitions ). 但是,它的语义将其视为没有任何行为(例如,请参阅NonConstructorMethodDefinitions )。 Effectively you can have as many or as few semicolons you want in a ClassBody and it won't change a thing. 实际上,你可以在ClassBody中拥有你想要的ClassBody数量的分号,它不会改变任何东西。

Automatic semicolon insertion actually doesn't come into play here, or as often as people think in general. 自动分号插入实际上并没有在这里发挥作用,或者像人们通常认为的那样经常发生。 Roughly speaking, ASI only happens when the parser sees something that wouldn't be allowed to be part of the previous block or line. 粗略地说,ASI只发生在解析器看到不允许成为前一个块或行的一部分的情况时。 (The actual rules for ASI aren't terribly long if you're interested; scroll down for examples and practical advice.) However in this context, you're allowed to put a bunch of class method definitions together sequentially. (如果您感兴趣的话,ASI的实际规则并不长;向下滚动以获取示例和实用建议。)但是在此上下文中,您可以按顺序将一堆类方法定义放在一起。 Thus there's nothing "unexpected" about the next method in the list, so no semicolon gets inserted between them. 因此,列表中的下一个方法没有任何“意外”,因此不会在它们之间插入分号。

I don't know the history of the decision, but I assume semicolons are valid ClassElement s because they were already valid as empty statements, and it would probably be confusing for folks if you couldn't put semicolons in a class body. 我不知道决定的历史,但我认为分号是有效的ClassElement因为它们已经作为空语句有效,如果你不能将分号放在类体中,它可能会让人感到困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM