为什么在JavaScript IIFE周围需要括号? [英] Why are parentheses required around JavaScript IIFE?

查看:70
本文介绍了为什么在JavaScript IIFE周围需要括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读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.

http://benalman.com/news/2010/11/立即调用功能表达式/

有关详细说明,请参见:

For more detailed explanation please see:

高级JavaScript:为什么包装此函数放在括号里?

提示:

调用运算符(())仅适用于表达式,而不适用于声明.

The invocation operator (()) only works with expressions, not declarations.

这篇关于为什么在JavaScript IIFE周围需要括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆