클로저의 유용한 사용의 예

  • Currying: 함수 하나가 n개 인자를 받는 대신, n개의 함수를 만들어 각각 인자를 받게 하는 방법
function adder(x) {
  return function(y) {
    return x + y;
  }
}
adder(2)(3); // 5
let add100 = adder(100); // 하나의 전달인자(x)값을 고정해놓고 재사용할 수 있다.
add100(2);  //102
  • 외부 함수의 변수가 저장되어 마치 Template Function과 같이 사용 가능
function htmlMaker(tag) {
  let startTag = '<' + tag + '>';
  let endTag = '</' + tag + '>';
  return function(content) {
    return startTag + content + endTag;
  }
}
let h1Maker = htmlMaker('h1');
h1Maker('Hello world') // <h1>Hello world</h1>
  • Module Pattern : 변수를 스코프 안쪽에 가두어 함수 밖으로 노출 시키지 않는 방법(외부에서 변수의 값을 재할당할 수 없다. 즉 재할당하는 방법으로는 값을 바꿀 수 없다.)
function makeCounter() {
  let privateCounter = 0;
  return {
    increment: function() {
   	  privateCounter++;
    },
    decrement: function() {
      privateCounter--;
    }
    getValue: function() {
      return privateCounter;
    }
}
let counter = makeCounter();
counter.increment();
counter.increment();
counter.getValue(); // 2

코드 및 자료 출처: 코드스테이츠(CodeStates)

0개의 댓글