[JS] this

yengni·2022년 7월 14일
0

JS

목록 보기
8/11
post-thumbnail

🌳 this

  • 일반함수 : 호출위치에 따라 this 정의
  • 화살표함수 : 자신이 선언된 함수범위에서 this 정의

예제 ) 일반함수와 화살표함수의 this

const heropy = {
	name : 'heropy'
    // 일반함수
    normal : function(){
    	console.log(this.named);
    }
    // 화살표함수
    arrow : funcition(){
    	console.log(this.name);
    }
}
heropy.normal();	//heropy  호출된 위치의 this는 heropy이기 때문에 heropy의 name은 'heropy'이다.
heropy.arrow();	//undefined	 현재 arrow의 함수범위가 정의되어있지 않다.

🕊 일반함수의 this

undefined : 중첩된 구조이기 때문에 현재 호출 위치의 this인 setTimeout에는 name이라는 속성이 없기 때문에 undefined이다.

const timer = {
	name : 'heropy',
timeout : function(){
	setTimeout(function(){
    	console.log(this.name)
    }, 2000 )
  }
}
timer.timeout();  //undefined

🕊 화살표 함수의 this

herophy : 자신이 선언된 함수범위는 setTimeout을 감싸고 있는 function()이고 이 function()의 this는 timer이다. 그러므로 timer.name은 heropy이다.

const timer = {
	name : 'heropy',
timeout : function(){
	setTimeout(() => {
    	console.log(this.name)
    }, 2000 )
  }
}
timer.timeout();  //heropy
profile
우당탕탕 비전공자의 FE 개발일지

0개의 댓글

관련 채용 정보