[英]What's the explanation for {} as an arrow function version of JavaScript IIFE?
The normal arrow function version of an IIFE is this: IIFE 的正常箭头 function 版本是这样的:
(() => {
console.log('IIFE 1');
})();
But I've found here that also the following (really short) form works:但我在这里发现以下(非常短的)表格也有效:
As a bit of extra credit there's an even shorter way to write IIFEs in ES6 which is to use the new function context syntax all on its own like so:
作为额外的功劳,在 ES6 中编写 IIFE 有一种更短的方法,即单独使用新的 function 上下文语法,如下所示:
{
console.log('IIFE 2');
}
Why only {}
is enought?为什么只有
{}
就足够了?
Well what's the point of calling an IIFE?那么调用 IIFE 有什么意义呢? it's to run some code in it's own context, right?
它是在它自己的上下文中运行一些代码,对吗?
Thats what curly brackets do, they group blocks of code.这就是大括号的作用,它们将代码块分组。 From ES6, variables declared with
const
or let
are not available from outside a block of code.从 ES6 开始,使用
const
或let
声明的变量不能从代码块外部获得。 So所以
(() => {
var x = 'IIFE 1'
console.log(x);
})();
and和
{
let x = 'IIFE 1'
console.log(x);
}
are equivalent是等价的
Because it satisfies both conditions required by an IIFE (Immediately Invoked Function Expression):因为它满足 IIFE 所需的两个条件(立即调用 Function 表达式):
https://developer.mozilla.org/en-US/docs/Glossary/IIFE https://developer.mozilla.org/en-US/docs/Glossary/IIFE
The only limitation, as the author indicates, is that you can't pass external parameters to the block.正如作者所指出的,唯一的限制是您不能将外部参数传递给块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.