首页 > 解决方案 > Why do we need to wrap IIFE with ()

问题描述

When we use a standalone function statement as IIFE we need to wrap it with() to make it work

// IFFE
(function a(){
    console.log('Hello')
}());

// IFFE
(function a(){
    console.log('Hello')
})()

If we don't wrap with () code produces a syntax error

function a(){
    console.log('Hello')
}()

But when we use as function expression we do not need to wrap it with ()

let a = function a(){
    console.log('Hello')
}()

So why we need to wrap it with () when we want to use it as function statement ?

标签: javascriptfunctioniife

解决方案


当解释器在解析 Javascript 文本时,遇到新行 andfunction a时,它将开始将其解释为名为 的函数的函数声明a。最终,它将以}. 如果您在()其后放置 a ,它将尝试将 解析(为表达式的开头 - 但表达式必须评估为something,它不能为空,因此当它看到 时),它会抛出。

(您可以在括号中添加一些内容,但它只是一个未使用的表达式,并且不会调用该函数:

function foo() {
  console.log('foo');
}(123);

console.log('done');

)

放在(前面function a确保解释器将后面的 解析function a表达式(一个可以使用的值,就像()后面的那个),而不是一个语句(它了一些事情 - 比如声明该范围内可用的函数 - 但确实不求值)。


推荐阅读