일반함수
: 호출위치에 따라 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의 함수범위가 정의되어있지 않다.
undefined : 중첩된 구조이기 때문에 현재 호출 위치의 this인 setTimeout에는 name이라는 속성이 없기 때문에 undefined이다.
const timer = { name : 'heropy', timeout : function(){ setTimeout(function(){ console.log(this.name) }, 2000 ) } } timer.timeout(); //undefined
herophy : 자신이 선언된 함수범위는 setTimeout을 감싸고 있는 function()이고 이 function()의 this는 timer이다. 그러므로 timer.name은 heropy이다.
const timer = { name : 'heropy', timeout : function(){ setTimeout(() => { console.log(this.name) }, 2000 ) } } timer.timeout(); //heropy