好吧,首先,我应该问这是否是浏览器依赖性的。
我已经读到,如果找到一个无效的令牌,但是代码部分有效,直到该代币无效,如果在令牌之前插入了一个半隆之前,则在该令牌之前插入了一个semicolon。
但是,由半插入引起的错误引用的常见示例是:
return
_a+b;
..似乎不遵循此规则,因为_a将是有效的令牌。
另一方面,分解呼叫链的工作原理:
$('#myButton')
.click(function(){alert("Hello!")});
有人对规则有更深入的描述?
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.
However, the common example cited for bugs caused by semicolon insertion is:
return
_a+b;
..which doesn't seem to follow this rule, since _a would be a valid token.
On the other hand, breaking up call chains works as expected:
$('#myButton')
.click(function(){alert("Hello!")});
Does anyone have a more in-depth description of the rules?
发布评论
评论(7)
首先,您应该知道哪些语句受自动插入的影响(也称为简洁的ASI):
var
var 语句do-while
继续
语句break
语句throw
语句ASI的具体规则,在规范
描述了三种情况:
lineTerminator
。}
eg :
已转换为
numericLiteral
1 符合第一个条件,以下令牌是线终结者。2
符合第二个条件,以下令牌为}
。eg :
已转化为:
限制作品:
returnstatement
的经典示例:带有
First of all you should know which statements are affected by the automatic semicolon insertion (also known as ASI for brevity):
var
statementdo-while
statementcontinue
statementbreak
statementreturn
statementthrow
statementThe concrete rules of ASI, are described in the specification §11.9.1 Rules of Automatic Semicolon Insertion
Three cases are described:
LineTerminator
.}
e.g.:
is transformed to
The
NumericLiteral
1
meets the first condition, the following token is a line terminator.The
2
meets the second condition, the following token is}
.e.g.:
is transformed to:
Restricted productions:
The classic example, with the
ReturnStatement
:is transformed to
我无法很好地理解规格中的这3个规则 - 希望能拥有更普通英语的东西 - 但这是我从JavaScript中收集的内容:第6版,David Flanagan,O'Reilly,2011年:
引用:
另一个报价:代码
和:
因此,我认为要简化它,这意味着:
通常,JavaScript只要有意义,JavaScript将其视为持续的代码 - 除2个情况外:(1)在一些关键字之后,例如
返回
,break
,<代码>继续,(2)如果看到++
或 - ; 。>在新行上,它将在 “使其感觉就像是正则表达式的贪婪匹配。
与上述说明,这意味着
返回
在折线中,JavaScript解释器将插入;
(再次引用:如果在任何这些单词之后出现了一条折断(例如
return
] ... JavaScript总是将阵列断开解释为半隆),并且由于这个原因,这是
Will 的经典示例无法按预期工作,因为JavaScript解释器将其视为:
后,必须立即破坏线路
返回
:才能正常工作 。如果要遵循;
在任何语句之后使用:I could not understand those 3 rules in the specs too well -- hope to have something that is more plain English -- but here is what I gathered from JavaScript: The Definitive Guide, 6th Edition, David Flanagan, O'Reilly, 2011:
Quote:
Another quote: for the code
and:
So I think to simplify it, that means:
In general, JavaScript will treat it as continuation of code as long as it makes sense -- except 2 cases: (1) after some keywords like
return
,break
,continue
, and (2) if it sees++
or--
on a new line, then it will add the;
at the end of the previous line.The part about "treat it as continuation of code as long as it makes sense" makes it feel like regular expression's greedy matching.
With the above said, that means for
return
with a line break, the JavaScript interpreter will insert a;
(quoted again: If a line break appears after any of these words [such as
return
] ... JavaScript will always interpret that line break as a semicolon)and due to this reason, the classic example of
will not work as expected, because the JavaScript interpreter will treat it as:
There has to be no line-break immediately after the
return
:for it to work properly. And you may insert a
;
yourself if you were to follow the rule of using a;
after any statement:直接从 ecma-262,第五版Ecmascript Specification :
Straight from the ECMA-262, Fifth Edition ECMAScript Specification:
关于半插入和var语句,请注意使用VAR时忘记逗号,但跨越多行。昨天有人在我的代码中发现了这一点:
它运行了,但效果是SRCIDS声明/作业是全球的,因为上一行的本地声明不再应用,因为由于自动半柱插入,该声明被认为是完成的。
Regarding semicolon insertion and the var statement, beware forgetting the comma when using var but spanning multiple lines. Somebody found this in my code yesterday:
It ran but the effect was that the srcIds declaration/assignment was global because the local declaration with var on the previous line no longer applied as that statement was considered finished due to automatic semi-colon insertion.
JavaScript的我发现来自一本关于
他继续描述它,就像您代码气味。
The most contextual description of JavaScript's Automatic Semicolon Insertion I have found comes from a book about Crafting Interpreters.
He goes on to describe it as you would code smell.
只是为了添加,
请参阅此信息,使用立即调用函数表达式(iife)
Just to add,
see this, using immediately invoked function expression(IIFE)
JavaScript中的大多数陈述和声明必须用半柱终止,但是,为了方便程序员(较少的打字,风格偏好,较少的代码噪声,较低的代码噪声,较低的入口障碍),在某些源文本位置可能会省略半元素,并在某些源文本位置省略。运行时会根据规格中的一组规则设置自动插入半洛龙。
规范规则:如果将半隆作为空语言解析,或者该半隆将成为 for 语句的标题中的两个分号之一,则永远不会自动插入半分号。
规则1
如果JavaScript解析器遇到一个令牌,则将自动插入半分离,如果不存在半分离符,则不允许两者都允许两者都允许,并且该令牌与以前的终结者(例如,新行)(例如,新线)将令牌与以前的差异分开。闭合支架
}
,或do-where循环的最终括号()
)。换句话说:源文本位置无论如何都需要终止语句的源文本位置,如果省略了语句终结器(
;
),则将自动插入。该规则是ASI的核心。规则2
如果源文本不是有效的脚本或模块,则将在程序末尾插入半分析。换句话说:程序员可以省略程序中的最后一个半隆。
规则3,
如果遇到一个令牌,如果遇到一个令牌,则如果不存在半隆,则将自动插入,但在几个特殊的源文本位置之一(限制性限制的生产)中存在,这是明确禁止行的一个特殊源文本位置之一终结者是出于避免歧义的原因。
禁止在哪个线路终止器内部的限制作品是:
++
和Postfix-
- (因此,Newline之后的Unary增量/减少操作员将绑定到<< em>以下(不是以前的)语句,作为前缀操作员)继续
,break
,throw
,返回
,<代码>屈服async
在async函数声明中的关键字&amp;表达式,发电机函数声明&amp;表达式&amp;方法和异步箭头函数规格包含完整的详细信息以及遵循实际建议:
。
ASI GOTCHA示例
启动了``(``
与关闭括号配对时)。
开头括号字符具有多个含义。它可以描述一个表达式,也可以指示调用(例如, .log(...)不是一个函数“因为运行时尝试调用
console.log('bar')
的返回值:一个解决方案,如果您通常省略了半隆,是包括一个分号以使您的意图明确:
使用``
开头括号字符(
[
)具有多种含义。声明数组(与闭合括号配对时),或者可以指示数组破坏。在
console.log('bar')
的响应中,名为“ foo”的属性的价值:如果通常省略半隆,则是一个解决方案,是包括一个半隆来使您的意图变得明确。 :
Most statements and declarations in JavaScript must be terminated with a semicolon, however, for the convenience of the programmer (less typing, stylistic preference, less code noise, lower barrier to entry), semicolons may be omitted in some source text locations, with the runtime automatically inserting semicolons according to a set of rules set-out in the spec.
Over-arching rules: a semicolon is never inserted automatically if the semicolon would then be parsed as an empty statement or if that semicolon would become one of the two semicolons in the header of a
for
statement.Rule 1
A semicolon will be automatically inserted if a token is encountered by the JavaScript parser that both would not be allowed if a semicolon did not exist, and that token is separated from the previous by one or more line terminators (eg. newlines), a closing brace
}
, or the final parenthesis ()
) of a do-while loop.In other words: source text locations where statements would always need to be terminated anyway for a runnable program, will have the statement terminator (
;
) inserted automatically if it is omitted. This rule is the heart of ASI.Rule 2
A semicolon will be inserted at the end of the program if the source text is not otherwise a valid script or module. In other words: programmers can omit the final semicolon in a program.
Rule 3
A semicolon will be automatically inserted if a token is encountered that would normally be allowed if a semicolon did not exist, but exists within one of several special source text locations (restricted productions) that explicitly disallow line terminators within them for reasons of avoiding ambiguity.
The restricted productions inside of which line terminators are prohibited are:
++
and postfix--
(so the unary increment/decrement operators after a newline will bind to the following (not previous) statement, as a prefix operator)continue
,break
,throw
,return
,yield
async
keyword in async function declarations & expressions, generator function declarations & expressions & methods, and async arrow functionsThe spec contains the full details, plus the following practical advice:
And this is the best article on the Web on this subject.
ASI Gotcha Examples
Starting a line with `(`
The opening parenthesis character has multiple meanings. It can delineate an expression, or it can indicate an invocation (when paired with a closing parenthesis).
For example, the following throws "Uncaught TypeError: console.log(...) is not a function" because the runtime attempts to invoke the return value of
console.log('bar')
:One solution for this, if you are generally omitting semicolons, is to include a semicolon to make your intentions unambiguous:
Starting a line with `[`
The opening bracket character (
[
) has multiple meanings. It can indicate an object property access, or it can indicate the literal declaration of an array (when paired with a closing bracket), or it can indicate an array destructuring.For example, the following throws "Uncaught TypeError: Cannot set properties of undefined (setting 'foo')" because the runtime attempts to set the value of a property named 'foo' on the response of
console.log('bar')
:One solution for this, if you are generally omitting semicolons, is to include a semicolon to make your intentions unambiguous: