简体   繁体   English

我需要将 IIFE 与 ES6 模块一起使用吗?

[英]Do I need to use IIFE with ES6 modules?

In the airbnb style guide it states that IIFE are mostly never needed.在 airbnb 风格指南中,它指出几乎不需要 IIFE。

https://github.com/airbnb/javascript/blob/master/README.md#functions https://github.com/airbnb/javascript/blob/master/README.md#functions

7.2 Wrap immediately invoked function expressions in parentheses. 7.2 将立即调用的 function 表达式包装在括号中。 eslint: wrap-iife eslint:包装生命

Why?为什么? An immediately invoked function expression is a single unit - wrapping both it, and its invocation parens, in parens, cleanly expresses this.立即调用的 function 表达式是一个单独的单元 - 包装它,它的调用括号,在括号中,清楚地表达了这一点。 Note that in a world with modules everywhere, you almost never need an IIFE.请注意,在一个到处都是模块的世界中,您几乎不需要 IIFE。

// immediately-invoked function expression (IIFE)
(function () {
  console.log('Welcome to the Internet. Please follow me.');
}());

Can someone explain why this would be the case?有人可以解释为什么会这样吗? I cannot find an explanation anywhere that says if I create a function at the top level in a module js script it would not be in the global namespace.如果我在模块 js 脚本的顶层创建 function,我在任何地方都找不到解释,它不会在全局命名空间中。

The most common use of an IIFE is to create a scope for variables to exist in so they don't become globals. IIFE 最常见的用途是为变量创建一个 scope以使其不会成为全局变量。

A module has its own scope, and a variable declared in the top level of a module is scoped to that module and not globally.一个模块有它自己的 scope,并且在模块顶层声明的变量的作用域是该模块而不是全局的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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