전역 컨텍스트 (Global Context)
- 전역 객체 참조
- 브라우저:
window
- Node.js:
global
함수 컨텍스트 (Function Context)
- 전역 객체 참조
- 엄격 모드(strict mode)에서는
undefined
를 참조
메소드 컨텍스트 (Method Context)
const obj = {
name: '폼폼푸린',
getName: function() {
console.log(this.name);
}
};
obj.getName(); // 폼폼푸린
생성자 함수 (Constructor Function)
function Person(name) {
this.name = name;
}
const person = new Person('폼폼푸린');
console.log(person.name); // 폼폼푸린
명시적 바인딩 (Explicit Binding)
call
, apply
, bind
를 사용해 this
를 명시적으로 바인딩 가능
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const a1 = { name: '기린' };
const a2 = { name: '곰' };
const a3 = { name: '푸린' };
// call 메서드를 사용하여 즉시 호출
greet.call(a1, '안녕', '!'); // 안녕, 기린!
// apply 메서드를 사용하여 즉시 호출, 인수는 배열로 전달
greet.apply(a2, ['안녕', '...']); // 안녕, 곰...
// bind 메서드를 사용하여 새로운 함수를 생성, 나중에 호출
const greetPurin = greet.bind(a3);
greetPurin('안뇽', '.'); // 안뇽, 푸린.