javascript - 难以理解分号插入

标签 javascript

根据 this , JavaScript 将在以下情况下插入分号:

When the program contains a token that is not allowed by the formal grammar, then a semicolon is inserted if (a) there is a line break at that point, or (b) the unexpected token was a closing brace. (emphasis mine)

经典的例子是

return  //  <--- semicolon inserted there
{
   id: 12
};

这让我相信独立的 { 是无效的。然而以下(无意义的)代码警告 2,没有错误

function foo() {
    var x = 1;
    {
        var y = 2; //yes, I know y has the same scope as x 
    }              //and that this is therefore pointless
    alert(y);
}

为什么左大括号在第一段代码中被视为无效标记,导致 JavaScript 插入分号,但在第二段代码中左大括号未被视为无效——事实证明没有错误。

显然我的一个假设是错误的,我希望有人能帮助我理解是哪一个。

最佳答案

您提到的 return 语句问题不受分号插入规则的那个特定方面的影响。相反,是这个:

When, as the program is parsed from left to right, a token is encountered that is allowed by some production of the grammar, but the production is a restricted production and the token would be the first token for a terminal or nonterminal immediately following the annotation ―[no LineTerminator here]‖ within the restricted production (and therefore such a token is called a restricted token), and the restricted token is separated from the previous token by at least one LineTerminator, then a semicolon is automatically inserted before the restricted token.

碰巧 return 语句语法有一个“[这里没有 LineTerminator]”怪癖。

请参阅 ES 5 规范的第 7.9.1 节。

关于javascript - 难以理解分号插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8393677/

相关文章:

php - Safari 6 ajax 请求获取新的 session ID

javascript - "onchange"指令内的 Angular 回调

javascript - 无法在 &lt;script&gt; 标签上对生成的 RSS 进行样式化

javascript - ParsleyJS 自定义验证器跳过验证没有错误

javascript - 用于单个页面上单个音频元素的 jQuery 预加载器

javascript - LinkedIn 共享显示大图像的要求

javascript - 如何检查是否已下载所有 CSS 文件以使用 JavaScript 插入 HTML?

javascript - 如何修改指令中 ng-repeat 创建的每个元素的单独范围?

javascript - 让 focusout 事件忽略一些元素

javascript - 如何确定 iOS 上的实际视口(viewport)宽度和高度