const timer = {
name: 'Inhwa!!',
timeout: function() {
setTimeout(function(){
console.log(this.name)
}, 2000)
}
}
timer.timeout(); // 결과 : undefined
setTimeout의 내부함수 콜백함수 위치에 일반함수로 this가 정의되기 때문에 this.name을 찾을 수 없음 => 일반함수로 호출한 콜백함수를 화살표함수로 바꿔주어야 함
const timer = {
name: 'Inhwa!!',
timeout: function() {
setTimeout(()=> {
console.log(this.name)
}, 2000)
}
}
timer.timeout(); // 결과 : Inhwa!!
this는 timer를 가리키게 되어 this.name을 출력할 수 있다