Welcome to The JS Bifrost, your pathway to rock-solid foundation for God-level JavaScript. This is the next article in the series. This article is about one of the most popular coding pattern called “iffy”, which is a JavaScript function that executes immediately after creation.
欢迎使用JS Bifrost,这是通往神级JavaScript的坚实基础的途径。 这是该系列的下一篇文章。 本文介绍了一种称为“ iffy”的最受欢迎的编码模式,该模式是一种在创建后立即执行JavaScript函数。

定义 (Definition)
An IIFE is a coding pattern called an Immediately Invoked Function Expression which is a way to execute a JavaScript function immediately after it is created. Also pronounced as “iffy.” Let’s look at the traditional and more widely used syntax used to declare an IIFE.
IIFE是一种称为立即调用函数表达式的编码模式,它是一种在创建JavaScript函数后立即执行的方法。 也发音为“ iffy”。 让我们看一下用于声明IIFE的传统且使用更为广泛的语法。
The ES6 way: (() => {
/* statements */
})()The ES5 way:
(function() {
/* statements */
})()
句法 (Syntax)
Let’s break down the syntax for the above example step by step:
让我们逐步分解上面示例的语法:
When JavaScript encounters a function keyword in a valid statement, it expects that a function definition/declaration is going to take place. To stop the JavaScript engine from throwing a syntax error, a function expression is created by wrapping the function definition inside parentheses. The wrapping parentheses will be internally considered as an expression.
当JavaScript在有效的语句中遇到function关键字时,它期望函数定义/声明将要发生。 为了阻止JavaScript引擎引发语法错误,可以通过将函数定义包装在括号内来创建函数表达式。 包装括号将在内部被视为表达式。
2. Alternatively, there is another variation of writing an IIFE:
2.另外,编写IIFE还有另一种形式:
!function() {
alert("Hello, I am an IIFE!");
}();
// Prints Hello, I am an IIFE!
The “!” operator as a prefix, will tell JavaScript that “Anything after the not operator is part of an expression. (You can replace “!” with any unary operator which will make that function into an expression.) But this variation will not return any value from the IIFE.
“!” 运算符作为前缀,将告诉JavaScript“非运算符之后的所有内容都是表达式的一部分。 (您可以用任何一元运算符将“!”替换为可使该函数成为表达式的一元运算符。)但是,此变体不会从IIFE返回任何值。
3. At the end of the definition, add another pair of parentheses which are called the invoking parentheses and a semicolon. The invoking parentheses is what tells the compiler that the function expression has to be executed immediately.
3.在定义末尾,添加另一对括号,称为调用括号和一个分号。 调用括号告诉编译器必须立即执行函数表达式。
Example1:(function() {
/* statement */
}()); Example2:
(function() {
/* statement */
})();
“()”, for invoking the function expression is either placed inside or outside the wrapping parentheses for the function expression.
为了调用函数表达式,“()”位于函数表达式的包装括号内或括号外。
匿名还是命名? (Anonymous or Named?)
IIFE functions are anonymous functions — As per the definition, anonymous function has no identifier. This is a function expression which does not require a name.
IIFE函数是匿名函数-根据定义,匿名函数没有标识符。 这是一个不需要名称的函数表达式。
The wrapping parentheses will treat what is inside, as an expression and will immediately evaluate to return a value.
包装括号将把里面的内容当作一个表达式,并立即求值以返回一个值。
They can also be named functions. However, having a name is unnecessary as IIFE’s cannot be referred/invoked more than once after their execution. (Apart from function name showing up in stack-traces).
它们也可以被命名为函数。 但是,不需要名称,因为IIFE在执行后不能被多次引用/调用。 (除了函数名称显示在堆栈跟踪中)。
(function foo() {
/* statements */
})();
A quick example to show that IIFEs can also take arguments when they are invoked. We are now passing an argument to the IIFE when we execute it.
一个简单的示例说明IIFE在被调用时也可以接受参数。 现在,我们在执行参数时将其传递给IIFE。
(function(myTxt) {
console.log(myTxt);
})(“Hello!, I am an IIFE”);
// Prints Hello!, I am an IIFE
为什么? (Why?)
IIFE’s are useful because they don’t pollute or overwrite the global object and they are a simple way to isolate variable declarations.
IIFE很有用,因为它们不会污染或覆盖全局对象,并且它们是隔离变量声明的简单方法。
Data Privacy — IIFEs have their own scope i.e. the variables you declare in the Function Expression will not be available outside the function.
数据隐私-IIFE具有自己的范围,即您在函数表达式中声明的变量将在函数外部不可用。
(function () {
var myName = "John";
})(); // Variable myName is not accessible from the outside scope
// myName throws "Uncaught ReferenceError: myName is not defined"
These variables are now scoped to the containing function because var
variables will be function-scoped and they will not be available in the global scope.
现在将这些变量的作用域限定为包含函数,因为var
变量将在作用域内起作用,并且它们在全局范围内将不可用。
No Name Collision — Functions and variables defined inside IIFE do not conflict with other functions & variables even if they have same name.
无名称冲突-IIFE中定义的函数和变量与其他函数和变量即使名称相同也不会冲突。
If you have many global variables and functions with the same name, the JavaScript engine will only release the memory allocated for them until when the global object loses the scope. The global variables and functions will likely cause name collisions. With the use of IIFE, defining variables inside functions or between curly braces makes them inaccessible to the global namespace which will help minimise the pollution of the global scope.
如果您有许多具有相同名称的全局变量和函数,则JavaScript引擎将只释放为其分配的内存,直到全局对象失去作用域为止。 全局变量和函数可能会导致名称冲突。 通过使用IIFE,在函数内部或花括号之间定义变量将使它们无法访问全局名称空间,这将有助于最大程度地减少对全局范围的污染。
Assigning the IIFE to a variable stores the function’s return value, not the function definition itself.
将IIFE分配给变量将存储函数的返回值,而不是函数定义本身。
var MyVar = (function () {
var myName = "John";
return name;
})();
// Immediately creates the output // "John"
ES6 Block范围是新的IIFE (ES6 Block scope is the new IIFE)
In ES6, const and let keywords allow developers to declare variables in the block scope, which means those variables exist only within the corresponding block. When you declare a global variable using the var
keyword, you are adding that variable to the property list of the global object. In the case of the web browser, the global object is the window
. However, when you use the let or const
keywords to declare a variable, that variable is not attached to the global object as a property. Hence the variables will have their own scope and will not allow you to redeclare them making your data private.
在ES6中, const和let关键字允许开发人员在块范围内声明变量,这意味着这些变量仅存在于相应的块内。 当使用var
关键字声明全局变量时,就是将该变量添加到全局对象的属性列表中。 对于Web浏览器,全局对象是window
。 但是,当您使用let or const
关键字声明变量时,该变量不会作为属性附加到全局对象。 因此,变量将具有它们自己的范围,并且不允许您重新声明它们以使数据私有。
{
const myName = 'John';
console.log(myName);
}
This will help when you want to make your code private where nothing leaks into the global scope of the window.
当您希望将代码私有化时,这不会有任何帮助,这不会泄漏到窗口的全局范围内。
结论 (Conclusion)
The most common use cases for IIFE’s are:
IIFE的最常见用例是:
- Creating private variables and functions. 创建私有变量和函数。
- Minimizing the pollution of the global scope due to name collisions. 最大限度地减少名称冲突造成的全球范围污染。
That’s all there is to know about IIFEs to start using them in your code.
这就是关于IIFE的全部知识,可以开始在您的代码中使用它们。
Watch this space to make more progress on your way to ‘God level JavaScript’ with ‘The JS Bifrost’.
观看此空间,以使用“ The JS Bifrost”迈向“神级JavaScript”的道路上取得更多进展。
翻译自: https://medium.com/globant/the-js-bifrost-understanding-the-coding-pattern-called-iife-794b46006550