为什么在JavaScript IIFE周围需要括号?

编程入门 行业动态 更新时间:2024-10-27 10:23:46
本文介绍了为什么在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.

benalman/news/2010/11/立即调用功能表达式/

有关详细说明,请参见:

For more detailed explanation please see:

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

提示:

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

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

更多推荐

为什么在JavaScript IIFE周围需要括号?

本文发布于:2023-07-31 15:47:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1260067.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:括号   JavaScript   IIFE

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!