简体   繁体   English

{} 作为箭头 JavaScript IIFE 的 function 版本的解释是什么?

[英]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?为什么只有{}就足够了?

The first example creates a function (which calls console.log ), then immediately calls it.第一个示例创建一个function (调用console.log ),然后立即调用它。

The second example doesn't create a function.第二个示例没有创建 function。 It just has a block .它只有一个

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 开始,使用constlet声明的变量不能从代码块外部获得。 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 表达式):

  • To prevent external access to the variables within the IIFE, as well as avoid polluting the global scope.为了防止外部访问 IIFE 中的变量,以及避免污染全局 scope。
  • It is executed immediately.它立即执行。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM