
JavaScript에서 this는 함수가 호출될 때 결정되는 객체를 참조하는 키워드 입니다.
상황에 따라 this가 가리키는 대상은 달라지며, 함수를 어떤 방식으로 호출하느냐에 따라 다르게 설정 됩니다.
일반 함수에서는 전역객체(window 또는 global)를 참조합니다.
function showThis(){
console.log(this);
}
showThis(); // 브라우저에서는 'window, Node.js에서는 'global' 객체 출력
객체의 메서드에서 this는 메서드를 소유한 객체를 참조합니다.
const person = {
name : 'Joon',
greet : function(){
console.log(this.name); // 'this'는 person 객체를 참조
}
};
person.greet(); // 'Joon' 출력
생성자 함수 내에서 this는 새로 생성된 인스턴스 객체를 참조합니다.
function Person(name){
this.name = name;
}
const joon = new Person('Joon');
console.log(joon.name); // 'Joon'출력
화살표 함수는 this를 고정합니다. 따라서 화살표 함수 내부의 this는 상위 스코프의 this와 동일합니다.
const person = {
name : 'Joon',
greet : () => {
console.log(this.name); // 'this'는 상위 스코프의 'this'를 참조
}
};
person.greet(); // undefined 출력(전역 객체에는 name이 없음)
JavaScript에서는 call(), apply(), bind() 메서드를 통해 this를 명시적으로 지정할 수 있습니다.
call() : 함수를 호출하면서 첫 번째 인자로 this를 설정합니다.apply() : call()과 유사하지만, 인자를 배열 형태로 전달합니다.bind() : 새로운 함수를 반환하면서 this를 영구적으로 설정합니다. function greet(){
console.log('Hello, ${this.name}');
}
const person = {name : 'Joon'};
greet.call(person); // 'Hello, Joon'
greet.apply(person); // 'Hello, Joon'
const greetPerson = greet.bind(person);
greetPerson(); // 'Hello, Joon'
이벤트 핸들러에서 this는 이벤트가 발생한 요소를 참조합니다.
<button id="myButton">Click me</button>
<script>
const button = document.getElementById('myButton');
button.addEventListener('click', function(){
console.log(this); // 클릭한 버튼 요소
});
</script>
결과(콘솔창)
<button id="myButton">Click me</button> // 요소 전체가 출력됨.
this 요약
window 또는 global).this를 유지.this는 상황에 따라 다르게 해석되므로, 특히 화살표 함수와 일반 함수의 차이점을 이해하고 사용 해야 합니다.