객체 지향
객체 지향 프로그래밍(OOP, Object-oriented programming)은 절차 지향 프로그래밍과는 다르게 데이터와 기능을 한 곳에 묶어서 처리한다. 속성과 메서드가 하나의 '객체'라는 개념에 포함되며 클래스라고 부른다.
객체.메서드()와 같이 객체 내에 메서드를 호출하는 방법이다.
화살표 함수는 자신의 this가 없기 때문에 this를 전역 객체로 정의한다. 따라서 메서드 호출 방식을 이용할 때에는 화살표 함수를 쓰지 않는다.
//Example
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
위의 예시는 단 하나의 객체만 생성할 수 있다.
만약 똑같은 기능을 하는 카운터가 여러 개 필요하다면 재사용성을 고려해 클로저 모듈 패턴을 이용한다.(필요할 때 마다 복사/붙여널기 할 필요x)
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
Reference: 코드스테이츠