๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Front-end/JS

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ํด๋กœ์ € ํ™œ์šฉ Closure private ๋ณ€์ˆ˜, ๋ฉ”์„œ๋“œ ํ‰๋‚ด ๋‚ด๊ธฐ

by ciocio 2021. 8. 28.

๐Ÿ“Œ  Closure ํ™œ์šฉ ๋ฐฉ๋ฒ•

 

๋Œ€ํ‘œ์ ์ธ ์ด์  ์ค‘ ํ•˜๋‚˜๊ฐ€, private ๋ณ€์ˆ˜๋‚˜ ๋ฉ”์„œ๋“œ๋ฅผ ํ‰๋‚ด๋‚ผ ์ˆ˜ ์žˆ๋‹ค๋Š” ์ ์ด๋‹ค.

 

// counter์— ํ• ๋‹น๋œ ์ด ์ต๋ช… ํ•จ์ˆ˜๋Š” ์ •์˜๋˜๋Š” ์ฆ‰์‹œ ์‹คํ–‰๋œ๋‹ค.
// ์ด lexical environment๋Š” privateCounter๋ผ๋Š” ๋ณ€์ˆ˜์™€ changeBy๋ผ๋Š” ํ•จ์ˆ˜๋ฅผ ํฌํ•จํ•œ๋‹ค.
// 2๊ฐœ ๋‹ค private item์ด๋‹ค. ์ต๋ช… ํ•จ์ˆ˜ ์™ธ๋ถ€์—์„œ ์ ‘๊ทผ๋  ์ˆ˜ ์—†๋Š” ์•„์ด๋“ค์ด๋‹ค.
// ๋Œ€์‹  ์ต๋ช… ํ•จ์ˆ˜์—์„œ ๋ฐ˜ํ™˜๋œ 3๊ฐœ์˜ public ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด์„œ๋งŒ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋‹ค.

let counter = (function() {
  let privateCounter = 0;
  function changeBy(val) {
  	privateCounter += val;
  }
  return {
    // counter.increase, counter.decrease, counter.value ๋Š” ๊ฐ™์€ lexical ํ™˜๊ฒฝ์„ ๊ณต์œ ํ•œ๋‹ค.
    increase: function() {
      changeBy(1);
    },
    decrease: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  };
})();

counter.increase();
counter.increase();
console.log(counter.value());  // logs 2

 

// ์ต๋ช… ํ•จ์ˆ˜๋ฅผ ๋ณ„๋„์˜ ๋ณ€์ˆ˜ makeCounter์— ์ €์žฅํ•˜๊ณ , ์ด ๋ณ€์ˆ˜๋ฅผ ์ด์šฉํ•ด ์—ฌ๋Ÿฌ๊ฐœ์˜ ์นด์šดํ„ฐ๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.
// 2๊ฐœ์˜ counter๋Š” ๊ฐ์ž์˜ ๋…๋ฆฝ์„ฑ์„ ์ง€ํ‚จ๋‹ค.
// ํ•˜๋‚˜์˜ ํด๋กœ์ €์—์„œ ๋ณ€์ˆ˜๊ฐ’์„ ๋ณ€๊ฒฝํ•ด๋„ ๋‹ค๋ฅธ ํด๋กœ์ €์˜ ๊ฐ’์—๋Š” ์˜ํ–ฅ์„ ์ฃผ์ง€ ์•Š๋Š”๋‹ค.
// -> ์ด๋Ÿฐ ๋ฐฉ์‹์œผ๋กœ ํด๋กœ์ €๋ฅผ ์‚ฌ์šฉํ•ด ๊ฐ์ฒด ์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ์˜ ์ •๋ณด ์€๋‹‰๊ณผ ์บก์Šํ™” ๊ฐ™์€ ์ด์ ์„ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค.

let makeCounter = function() {
  let privateCounter = 0;
  function changeBy(val) {
  	privateCounter += val;
  }
  return {
    // counter.increase, counter.decrease, counter.value ๋Š” ๊ฐ™์€ lexical ํ™˜๊ฒฝ์„ ๊ณต์œ ํ•œ๋‹ค.
    increase: function() {
      changeBy(1);
    },
    decrease: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  }
};

let counter1 = makeCounter();
let counter2 = makeCounter();

counter1.increase();
counter1.increase();
counter2.decrease();

console.log(counter1.value());  // 2
console.log(counter2.value());  // -1

 

 

๐Ÿ“Œ  Closure ์ž˜๋ชป๋œ ํ™œ์šฉ ๋ฐฉ๋ฒ•

 

MDN ํด๋กœ์ € ์„ฑ๋Šฅ ๊ด€๋ จ ๊ณ ๋ ค ์‚ฌํ•ญ

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€