JavaScript 自动分号插入 (ASI) 的规则是什么? [英] What are the rules for JavaScript's automatic semicolon insertion (ASI)?
问题描述
好吧,首先我应该问一下这是否取决于浏览器.
Well, first I should probably ask if this is browser dependent.
我已经读过,如果找到无效标记,但该部分代码在该无效标记之前一直有效,如果前面有换行符,则会在该标记之前插入一个分号.
I've read that if an invalid token is found, but the section of code is valid until that invalid token, a semicolon is inserted before the token if it is preceded by a line break.
但是,由于分号插入导致的错误引用的常见示例是:
return
_a+b;
..这似乎不符合此规则,因为 _a 将是一个有效的标记.
..which doesn't seem to follow this rule, since _a would be a valid token.
另一方面,分解调用链按预期工作:
$('#myButton')
.click(function(){alert("Hello!")});
有人对规则有更深入的描述吗?
Does anyone have a more in-depth description of the rules?
推荐答案
首先你应该知道哪些语句会受到自动分号插入(也称为 ASI)的影响:
First of all you should know which statements are affected by the automatic semicolon insertion (also known as ASI for brevity):
- 空语句
var
语句- 表达式语句
do-while
语句continue
声明break
语句return
语句throw
语句
- empty statement
var
statement- expression statement
do-while
statementcontinue
statementbreak
statementreturn
statementthrow
statement
ASI 的具体规则,在规范中有描述 §11.9.1 自动分号插入规则
The concrete rules of ASI, are described in the specification §11.9.1 Rules of Automatic Semicolon Insertion
描述了三种情况:
- 当遇到语法不允许的违规标记时,在以下情况下会在其前插入分号:
- 该令牌与前一个令牌之间至少有一个
LineTerminator
. - 令牌是
}
例如:
{ 1
2 } 3
转化为
{ 1
;2 ;} 3;
NumericLiteral
1
满足第一个条件,后面的记号为行终止符.2
满足第二个条件,下面的token就是}
.
The NumericLiteral
1
meets the first condition, the following token is a line terminator.
The 2
meets the second condition, the following token is }
.
- 当遇到令牌输入流的末尾并且解析器无法将输入令牌流解析为单个完整程序时,则会在输入流的末尾自动插入分号.
例如:
a = b
++c
转换为:
a = b;
++c;
- 这种情况发生在语法的某些产生式允许令牌,但产生式是受限产生式,分号自动插入受限令牌之前.
- This case occurs when a token is allowed by some production of the grammar, but the production is a restricted production, a semicolon is automatically inserted before the restricted token.
受限制作:
UpdateExpression :
LeftHandSideExpression [no LineTerminator here] ++
LeftHandSideExpression [no LineTerminator here] --
ContinueStatement :
continue ;
continue [no LineTerminator here] LabelIdentifier ;
BreakStatement :
break ;
break [no LineTerminator here] LabelIdentifier ;
ReturnStatement :
return ;
return [no LineTerminator here] Expression ;
ThrowStatement :
throw [no LineTerminator here] Expression ;
ArrowFunction :
ArrowParameters [no LineTerminator here] => ConciseBody
YieldExpression :
yield [no LineTerminator here] * AssignmentExpression
yield [no LineTerminator here] AssignmentExpression
经典示例,带有ReturnStatement
:
return
"something";
转化为
return;
"something";
这篇关于JavaScript 自动分号插入 (ASI) 的规则是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!