我正在阅读JavaScript IIFE和到目前为止的理解概念,但是我想知道外部括号.具体来说,为什么需要它们?例如,
I'm reading up on JavaScript IIFE and so far the understand concept, but I am wondering about the outside parenthesis. Specifically, why are they required? For example,
(function() {var msg='I love JavaScript'; console.log(msg);}());效果很好,但是
function() {var msg='I love JavaScript'; console.log(msg);}();生成语法错误.为什么?关于IIFE的讨论很多,但是我对为什么需要括号没有清楚的解释.
generates a syntax error. Why? There are lots of discussions on IIFE, but I'm not seeing a clear explanation about why the parentheses are required.
推荐答案用括号括起来的IIFE版本有效,因为这会将内部函数声明的声明标记为表达式.
The version of IIFE that is wrapped in parenthesis works, because this marks the declaration of the internal function declaration as an expression.
benalman/news/2010/11/立即调用功能表达式/
有关详细说明,请参见:
For more detailed explanation please see:
高级JavaScript:为什么包装此函数放在括号里?
提示:
调用运算符(())仅适用于表达式,而不适用于声明.
The invocation operator (()) only works with expressions, not declarations.
更多推荐
为什么在JavaScript IIFE周围需要括号?
发布评论