FE
일반 함수와 화살표 함수가 this를 정의하는 범위
SIOT IEUNG
2021. 11. 7. 00:02
728x90
🚨 this 정의
📍 일반 함수와 화살표 함수에서의 this정의
일반 함수는 호출 위치에 따라 this를 정의한다.
화살표 함수는 자신이 선언된 함수 범위에서 this를 정의한다.
const siot = {
name : 'siot',
normal : function () {
console.log(this.name)
},
arrow : () => {
console.log(this.name)
}
}
siot.normal() // siot
siot.arrow() // undefined
* 일반함수를 할당할 때는 콜론과 function이 생략가능하다.
const siot = {
name : 'siot',
normal() {
console.log(this.name)
}
}
siot.normal() // siot
💡 화살표 함수를 사용해야만 하는 경우
📍 콜백 일반 함수
다음의 setTimeout메서드에서 콜백함수로 일반 함수를 할당하게 되면(호출 위치에서 정의) this는 setTimeout로직 안에서 실행된다. 결과적으로 timer.timeout()은 값이 정의될 수 없다.
const timer = {
name : 'siot',
timeout : function () {
setTimeout(function () {
console.log(this.name)
}, 2000)
}
}
timer.timeout() // undefined
📍 콜백 화살표 함수
콜백함수로 화살표 함수를 할당하게 되면 그 자체에서 this가 정의되기 때문에 제대로 동작된다. 대표적으로 setTimeout과 같이 콜백을 인수로 쓰는 형태에서는 화살표 함수를 쓸 경우 this를 사용할 수 있게 된다.
const timer = {
name : 'siot',
timeout : function () {
setTimeout(() => {
console.log(this.name)
}, 2000)
}
}
timer.timeout() // siot
728x90