了解自调用函数语句之间的区别
Understanding the difference between self invoking functions statements
请解释,为什么会出现这种说法
function f(){}()
抛出异常,但括号内完全一样
(function f(){}())
没有
解析器将前者解释为 function declaration and the later as a function expression。
为什么?要理解,我们需要查看 ECMA-262 第 3 版的第 11.1.6 节和第 12.4 节。 12.4 节指出 "an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration." 这告诉我们 function f(){}()
必须是函数声明,而 ()
是无效语法。这个语句是表达式的原因是因为第 11.1.6 节中的分组运算符(又名括号)强制将此函数视为表达式。
请解释,为什么会出现这种说法
function f(){}()
抛出异常,但括号内完全一样
(function f(){}())
没有
解析器将前者解释为 function declaration and the later as a function expression。
为什么?要理解,我们需要查看 ECMA-262 第 3 版的第 11.1.6 节和第 12.4 节。 12.4 节指出 "an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration." 这告诉我们 function f(){}()
必须是函数声明,而 ()
是无效语法。这个语句是表达式的原因是因为第 11.1.6 节中的分组运算符(又名括号)强制将此函数视为表达式。