티스토리 뷰
ES6 Immediately-invoked function expression
IIFE was one of the most used patterns in the ES5 standard, as functions were the only way to declare a scoped block of code. So the following code will result with a ReferenceError
:
(function() {
var scoped = 42;
}());
console.log(scoped); // ReferenceError
ECMAScript introduced the block scoped let
and const
, so instead of using an IIFE, we can have the following code:
{
let scoped = 42;
}
console.log(scoped); // ReferenceError
The later example is way more clear and understandable.
IIFEs were used as a building block in the revealing module pattern. Its advantage is that it clearly separates between what is public and what is private:
var myModule = (function() {
// private variable, accessible only inside the IIFE
var counter = 0;
function increment() {
counter++;
}
// publicly exposed logic
return {
increment: increment
}
}());
Instead of using this pattern, with ES6 we can use modules. Modules declare their own scope and variables created inside the module will not polute the global object:
// myModule.js
let counter = 0;
export function increment() {
counter++;
}
// logic.js
import {increment} from 'myModule.js';
increment();
The only case, where you may want to use an IIFE is with an immediately-invoked arrow functions. Sometimes you only can produce a result via a sequence of statements, not via a single expression and if you want to inline these statements, you have to immediately invoke a function:
const SENTENCE = 'Hello world, how are you?';
const REVERSE = (() => {
const array = [...SENTENCE];
array.reverse();
return arr.join('');
})();
Keep in mind, that you need to wrap the arrow function in parentheses (they doesn't wrap the whole function).
As a rule of thumb you want to avoid using IIFEs in ES6, as there are other way to handle global variable polution.
https://hashnode.com/post/do-es6-modules-make-the-case-of-iifes-obsolete-civ96wet80scqgc538un20es0
https://ultimatecourses.com/blog/everything-you-wanted-to-know-about-javascript-scope
'■ 프론트엔드 ■ > JavaScript' 카테고리의 다른 글
HTML5 + sheet.js 를 이용한 클라이언트 Excel parse (12) | 2020.03.26 |
---|---|
es6, this and bind (0) | 2020.03.04 |
자바스크립트 currying 기법 (1) | 2019.03.13 |
new 연산자를 피하라 (1) | 2018.01.26 |
2017.07 자바스크립트 프레임워크 트렌드차트 (0) | 2017.07.06 |