화살표 함수의 this는 상위 스코프의 this를 가리킨다.
const person = {
name: 'bear',
sayName() {
console.log(this.name);
const inner = () => {
console.log(this.name);
]
inner();
}
}
person.sayName();
호출 시 sayName의 this는person 객체이기 때문에 sayName 내부에 있는 inner 함수의 this도 상위 스코프(sayName)의 this와 같게 되어 person 객체가 된다.
따라서 두 함수의 console.log(this.name)는 모두 bear가 나오게 된다.
const $button = document.querySelector('.btn');
$button.addEventListener('click', function() {
console.log(this);
});
위 코드에서 이벤트 핸들러 내부의 this는 이벤트를 바인딩한 DOM 요소(여기서는 $button)라는 것이 잘 알려져 있다.
하지만 왜 this가 DOM 요소인지에 대한 이유는 " 알 수 없다 "가 정답이다. 이벤트 핸들러 부분은 선언이지 호출이 아니기 때문이다. 따라서 핸들러가 아닌 addEventListener에서 호출되고, addEventListener 함수의 내부 로직에서 핸들러의 this가 DOM 요소를 가리키도록 하는 부분이 있다고 할 수 있는 것이다.
const $button = {
addEventListener: function(eventType, callback) {
...
callback.call($button);
callback.call(this); // addEventListener 호출 시 this는 $button
...
}
}
실제로 addEventListener 함수가 JS로 구현이 되어있지 않겠지만, 만약 JS로 구현할 수 있다면 상단의 코드와 같이 callback의 this를 addEventListener와 동일하게 설정하는 로직이 포함될 것이다.
const $button = document.querySelector('.btn');
$button.addEventListener('click', () => {
console.log(this);
}
화살표 함수의 경우, 상위 스코프의 this를 따르고, 상위 스코프는 anonymous(addEventListener는 함수의 호출이기 때문에 해당X)이기 때문에 window가 출력이 될 것이다.