[JS] this, 일반함수 호출과 화살표함수 호출 차이

ina·2023년 2월 6일
0

this

  • 일반(Normal)함수는 호출 위치에서 따라 this를 정의한다
  • 화살표(Arrow)함수는 자신이 선언된 함수 범위에서 this를 정의한다
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을 출력할 수 있다

profile
🐢 💨 💨

0개의 댓글