this 키워드
this는 함수 실행시 호출(invocation) 방법에 의해 결정되는 특별한 객체이다.
* 함수 실행시 결정되므로, 실행되는 맥락(execution context)에 따라 this는 다르게 결정된다.
함수 실행의 다섯가지 방법
1. Global : console.log(this)
* 정확히 말하면 함수 실행은 아니고, 전역에서 this를 참조할 때를 의미한다.
2. Function 호출 : foo()
3. Method 호출 : obj.foo()
4. new 키워드를 이용한 생성자 호출 : new Foo()
5. .call 또는 .apply 호출 : foo.call() / foo.apply()
함수 실행에 따른 this 바인딩 패턴
이 함수 실행의 다섯가지 방법에 따라 this 또한 다섯가지 바인딩 패턴이 존재한다.
패턴 | 바인딩 되는 객체 | 설명 |
Method 호출 | 부모 객체 (실행 시점에 온점 왼쪽에 있는 객체) | 하나의 객체에 값과 연관된 메소드를 묶어서 사용할 때 주로 사용함 |
new 키워드를 이용한 생성자 호출 | 새롭게 생성된 인스턴스 객체 | 객체 지향 프로그래밍에서 주로 사용함 |
.call 또는 .apply 호출 | 첫번째 인자로 전달된 객체 | this 값을 특정할 때 사용하며, 특히 apply의 경우 배열의 엘리먼트를 풀어서 인자로 넘기고자 할 때 유용함 |
** 아래 두가지 패턴의 사용은 권장하지 않는다.
패턴 | 바인딩되는 객체 (브라우저) | 바인딩되는 객체 (node.js) |
Global | window (strict mode에서는 undefined) | module.exports |
Function 호출 | window (strict mode에서는 undefined) | global |
Method 호출 방법 예시 (카운터를 구현)
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
똑같은 기능을 하는 카운터를 여러 개 만는 두 가지 방법 :
1. 클로저 모듈 패턴을 이용
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
2. 클래스로 만들어서 생성자 호출과 같이 사용
new 키워드를 통해서 새로운 객체가 생성되는 점이 다르다.
이 때의 객체는 인스턴스라고 부른다. 즉, 인스턴스.메소드() 의 형태의 호출이다.
class Counter {
constructor() {
this.value = 0; // 생성자 호출을 할 경우, this는 new 키워드로 생성한 Counter의 인스턴스입니다
}
increase() {
this.value++
}
decrease() {
this.value--
}
getValue() {
return this.value
}
}
let counter1 = new Counter() // 생성자 호출
counter1.increase()
counter1.getValue() // 1
'Programming > TIL' 카테고리의 다른 글
.bind Method (0) | 2020.12.01 |
---|---|
.call & .apply Methods (0) | 2020.12.01 |
Arrow Function (0) | 2020.12.01 |
Node.js Related Tools (0) | 2020.11.30 |
API [Application Programming Interface] (0) | 2020.11.30 |