简体   繁体   English

箭头 function 表达式与正常 function 表达式的自动分号插入 (ASI)

[英]Automatic Semicolon Insertion (ASI) for arrow function expression vs normal function expression

 const log = function (x) { console.log(x); } [1,2,3,4,5].forEach(num=>log(num))

This throws error:-这会引发错误:-

{
  "message": "Uncaught TypeError: Cannot read property 'forEach' of undefined",
  "filename": "https://stacksnippets.net/js",
  "lineno": 16,
  "colno": 13
}

Which is because of lack of semi-colon before the array.这是因为数组前缺少分号。 So it's misinterpreted as:-所以它被误解为:-

const log = function (x)
{
    console.log(x);
}[1,2,3,4,5].forEach(num=>log(num))

But why does the following work:-但为什么以下工作: -

 const log = (x)=>{ console.log(x) } [1,2,3,4,5].forEach(num=>log(num))

I understand that it's also a function expression as well.我知道它也是一个 function 表达式。 Is there an exception for arrow function in ASI? ASI中的箭头function有例外吗? Or am I missing something?还是我错过了什么?

The specification says: 规范说:

When, as the source text is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true: [...]当从左到右解析源文本时,遇到任何语法生成都不允许的标记(称为违规标记)时,如果一个或多个以下条件为真:[...]

So for ASI to happen, the syntax may be an invalid production without it.因此,要发生 ASI,如果没有它,语法可能是无效的产生式。 And actually it is:实际上它是:

  () => {}[0] // syntax error

So the Semicolon is needed here.所以这里需要分号。 Now why is that a Syntax error, while function () { }[0] is not?现在为什么这是一个语法错误,而function () { }[0]不是? Well, the member access is defined as那么,成员访问定义为

  MemberExpression:
    MemberExpression [ Expression ]
    PrimaryExpression
    //...

 PrimaryExpression:
   FunctionExpression
   // no arrow function here

Why the Syntax is how it is?为什么语法是这样的? I don't know.我不知道。

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

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