do es6 modules make the case of iifes obsolete - Lee-hyuna/33-js-concepts-kr GitHub Wiki

ES6 ๋ชจ๋“ˆ์ด IIFE๋ฅผ ๊ตฌ์‹œ๋Œ€์˜ ์œ ๋ฌผ๋กœ ๋งŒ๋“œ๋Š”๊ฐ€?

์›๋ฌธ: Do ES6 Modules make the case of IIFEs obsolete?

IIFE (Immediately Invoked Function Expression) ๋Š” ์ต๋ช…์˜ ํด๋กœ์ €๋ฅผ ํ†ตํ•ด "privacy"๋ฅผ ์ œ๊ณตํ•˜๋Š” ์„ค๊ณ„ ํŒจํ„ด์œผ๋กœ ์‚ฌ์šฉ๋œ๋‹ค. ES6 ๋ชจ๋“ˆ์˜ ์ถœํ˜„์€ IIFE์˜ ์‚ฌ์šฉ์„ ๊ตฌ์‹œ๋Œ€์˜ ์œ ๋ฌผ๋กœ ๋งŒ๋“œ๋Š”๊ฐ€?

์•„๋‹ˆ๋ฉด ์•„์ง๋„ IIFE๋ฅผ ์œ„ํ•œ ์‚ฌ์šฉ ์‚ฌ๋ก€๊ฐ€ ์žˆ์„๊นŒ?

IIFE๋Š” ํ•จ์ˆ˜๊ฐ€ ์ฝ”๋“œ์˜ ๋ธ”๋ก ์Šค์ฝ”ํ”„๋ฅผ ๋งŒ๋“œ๋Š” ์œ ์ผํ•œ ๋ฐฉ๋ฒ•์ด์—ˆ๊ธฐ ๋•Œ๋ฌธ์—, ES5 ํ‘œ์ค€์—์„œ ๊ฐ€์žฅ ๋งŽ์ด ์‚ฌ์šฉํ•˜๋Š” ํŒจํ„ด ์ค‘ ํ•˜๋‚˜์˜€๋‹ค. ๋”ฐ๋ผ์„œ ๋‹ค์Œ ์ฝ”๋“œ๋Š” ReferenceError๋ฅผ ๋ฐœ์ƒ์‹œํ‚ฌ ๊ฒƒ์ด๋‹ค.

(function() {
  var scoped = 42;
}());

console.log(scoped); // ReferenceError

ECMAScript๋Š” IIFE ๋Œ€์‹ ์— ์‚ฌ์šฉํ•  ๋ธ”๋ก ์Šค์ฝ”ํ”„๊ฐ€ ์ ์šฉ๋˜๋Š” let๊ณผ const๋ฅผ ๋„์ž…ํ–ˆ๋‹ค. ์•„๋ž˜์˜ ์ฝ”๋“œ๋ฅผ ๋ณด์ž.

{
  let scoped = 42;
}

console.log(scoped); // ReferenceError

์ด ์ฝ”๋“œ๊ฐ€ ์ด์ „ ์ฝ”๋“œ๋ณด๋‹ค ๋” ๋ช…ํ™•ํ•˜๊ณ  ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๋‹ค.

IIFE๋Š” ๋…ธ์ถœ ๋ชจ๋“ˆ ํŒจํ„ด์—์„œ ๋นŒ๋”ฉ ๋ธ”๋ก์œผ๋กœ ์‚ฌ์šฉ๋˜์—ˆ๋‹ค. ์ด๋Š” public๊ณผ private๋ฅผ ๋ช…ํ™•์ด ๊ตฌ๋ถ„ํ•˜๋Š” ๊ฒƒ์ด ์žฅ์ ์ด๋‹ค.

var myModule = (function() {
  // private ๋ณ€์ˆ˜, IIFE ์•ˆ์—์„œ๋งŒ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋‹ค.
  var counter = 0;

  function increment() {
    counter++;
  }

  // ์™ธ๋ถ€๋กœ ๋…ธ์ถœ๋˜๋Š” ๋กœ์ง
  return {    
    increment: increment
  }
}());

์ด ํŒจํ„ด์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ ๋Œ€์‹ ์—, ES6์˜ ๋ชจ๋“ˆ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ๋ชจ๋“ˆ์€ ์ž์‹ ์˜ ์Šค์ฝ”ํ”„๋ฅผ ์„ ์–ธํ•˜๊ณ  ๋ชจ๋“ˆ ๋‚ด๋ถ€์—์„œ ์ƒ์„ฑ ๋œ ๋ณ€์ˆ˜๋Š” ์ „์—ญ ๊ฐ์ฒด๋ฅผ ์˜ค์—ผ์‹œํ‚ค์ง€ ์•Š๋Š”๋‹ค.

// myModule.js

let counter = 0;

export function increment() {
  counter++;
}    

// logic.js

import {increment} from 'myModule.js';

increment();

IIFE๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ๋Š” ์ฆ‰์‹œ ํ˜ธ์ถœ๋˜๋Š” ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ์ด๋‹ค. ๋•Œ๋กœ๋Š” ๋‹จ์ผ ํ‘œํ˜„์‹์ด ์•„๋‹ˆ๋ผ ์ผ๋ จ์˜ ๊ตฌ๋ฌธ์„ ํ†ตํ•ด์„œ๋งŒ ๊ฒฐ๊ณผ๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ์ด๋Ÿฌํ•œ ๊ตฌ๋ฌธ์„ ์ธ๋ผ์ธํ™” ํ•˜๋ ค๋ฉด ์ฆ‰์‹œ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•ด์•ผ ํ•œ๋‹ค;

const SENTENCE = 'Hello world, how are you?';
const REVERSE = (() => {
  const array  = [...SENTENCE];
  array.reverse();
  return arr.join('');
})();

ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๋ฅผ ๊ด„ํ˜ธ( )๋กœ ๋ฌถ์–ด์•ผ ํ•จ์„ ๋ช…์‹ฌํ•ด๋ผ, (์ „์ฒด ํ•จ์ˆ˜๋ฅผ ๊ฐ์‹ธ์ง€ ์•Š์Œ).

๋Š๋‚€์ 

  • ์งง์•„์„œ ์ข‹๋‹ค.
  • ๊ธ€๋กœ๋ฒŒ ๋ณ€์ˆ˜์˜ ์˜ค์—ผ(polution)์ด๋ผ๋Š” ํ‘œํ˜„์„ ์ž์ฃผ ์“ฐ๋Š”๊ตฌ๋‚˜.