[JS] 클로저 모듈 패턴

[JS] 클로저 모듈 패턴

객체 지향 프로그래밍은, 절차 지향 프로그래밍과는 다르게 데이터와 기능을 한 곳에 묶어서 처리한다.
속성과 메서드가 하나의 “객체”라는 개념에 포함되며, 이는 자바스크립트 내장 타입인 object와는 다르게, 클래스(Class)라는 이름으로 부른다.

클로저 모듈 패턴

메서드 호출은 객체.메서드()와 같이 객체 내에 메서드를 호출하는 방법이다.
메서드 호출 방식을 이용할 때에는 ==화살표 함수==를 쓰지 않는다.

let counter1 = {
  value: 0,
  increase: function() {
    this.value++ // 메서드 호출을 할 경우, this는 counter1을 가리킵니다
  },
  decrease: function() {
    this.value--
  },
  getValue: function() {
    return this.value
  }
}

counter1.increase()
counter1.increase()
counter1.increase()
counter1.decrease()
counter1.getValue() // 2

클로저를 이용해 새로운 객체 생성

똑같은 기능을 하는 counter함수가 여러 개 필요할 떄, 같은 코드를 여러 번 복사, 붙여넣기 하는건 비효율적이다.
아래 코드는 똑같은 기능을 하는 카운터를 여러 개 만드는 방법 중 하나인 ==클로저 모듈 패턴==이다.

function makeCounter() {
  let value = 0;
  return {
    increase: function() {
      value++;
    },
    decrease: function() {
      value--;
    },
    getValue: function() {
      return value;
    }
  }
}

let counter1 = makeCounter()
counter1.increase()
counter1.getValue() // 1

let counter2 = makeCounter()
counter2.decrease()
counter2.decrease()
counter2.getValue() // -2

©lunadein2022 2022. All rights reserved.