javascript - 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 ?
解决方案
当解释器在解析 Javascript 文本时,遇到新行 andfunction a
时,它将开始将其解释为名为 的函数的函数声明a
。最终,它将以}
. 如果您在()
其后放置 a ,它将尝试将 解析(
为表达式的开头 - 但表达式必须评估为something,它不能为空,因此当它看到 时)
,它会抛出。
(您可以在括号中添加一些内容,但它只是一个未使用的表达式,并且不会调用该函数:
function foo() {
console.log('foo');
}(123);
console.log('done');
)
放在(
前面function a
确保解释器将后面的 解析function a
为表达式(一个可以使用的值,就像()
后面的那个),而不是一个语句(它做了一些事情 - 比如声明该范围内可用的函数 - 但确实不求值)。
推荐阅读
- javascript - 部署在 GitHub 页面上的 ReactJS 应用程序不适用于自定义域集
- c++ - 从邻接表 C++ 中删除元素
- sql - 按不同列值(时间戳)的 SQL 累积平均值
- laravel - 带有承载认证的 Laravel Json 测试
- javascript - 如何从 Firebase 以及 React Native 中的数组中删除数据
- audio - FFMPEG - 多轨、多通道文件到离散单声道文件
- python - 卡住未定义的变量,但找不到任何拼写错误或其他可能导致它的原因?
- postman - 从 Postman 调用受护照推特策略保护的 Passport API 端点
- swift - SwiftUI:启动时检查用户身份验证
- swift - PHAssetResource.assetResources() 调用的内存使用问题