객체 review

katsukichi·2021년 2월 25일
0

CodeStates_IM

목록 보기
9/48

⚠️ 메소드 호출 방식을 이용할 때에는 화살표 함수를 쓰지 않습니다. 그 이유는 "this 키워드" 항목에서 다룹니다.

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

이러한 하나의 객체만을 사용할수있는것을

singleton 패턴이라고 부릅니다.

클로저를 이용해 매번 새로운 객체 생성하기

function makeCounter() {
  return {
    value: 0,
    increase: function() {
      this.value++ // 메소드 호출을 할 경우, this는 makeCounter 함수가 리턴하는 익명의 객체입니다
    },
    decrease: function() {
      this.value--
    },
    getValue: function() {
      return this.value;
    }
  }
}

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

let counter2 = makeCounter()
counter2.decrease()
counter2.decrease()
counter2.getValue() // -2
profile
front-back / end developer / Let's be an adaptable person

0개의 댓글