일반(Normal) 함수는 호출 위치에 따라 this 정의!
화살표(Arrow) 함수는 자신이 선언된 함수 범위에서 this 정의!
const heropy = {
name: 'Heropy',
normal: function () { // 일반 함수
console.log(this.name);
},
arrow: () => { // 화살표 함수
console.log(this.name);
}
}
heropy.normal();
heropy.arrow();
결과
Heropy // heropy.normal();의 결과
undefined // heropy.arrow();의 결과
const heropy = {
name: 'Heropy',
normal: function () { // 일반 함수
console.log(this.name);
},
arrow: () => { // 화살표 함수
console.log(this.name);
}
}
heropy.normal();
heropy.arrow();
const may = {
name: 'Amy',
normal: heropy.normal,
arrow: heropy.arrow
}
amy.normal();
amy.arrow();
결과
Amy // amy.normal();의 결과
undefined // amy.arrow();의 결과
amy.normal();
로 호출했으므로 this는 호출된 위치인 amy가 됩니다.이 차이점을 잘 알고 있어야
JavaScript Class
에서 일반함수로 만들지, 화살표 함수로 만들지를 명확하게 결정할 수 있습니다.
왜냐하면JavaScript Class
에서는this
를 매우 많이 사용하기 때문입니다.
function User(name) {
this.name = name;
}
User.prototype.normal = function () {
console.log(this.name);
}
User.prototype.arrow = () => {
console.log(this.name);
}
const heropy = new User('Heropy');
heropy.normal();
heropy.arrow();
결과
Heropy // heropy.normal();
undefined // heropy.arrow();
const timer = {
name: 'Heropy!!',
timeout: function () {
//setTimeout(함수, 시간)
setTimeout(function () {
console.log(this.name);
}, 2000);
}
}
timer.timeout();
결과
undefined // timer.timeout();의 결과
const timer = {
name: 'Heropy!!',
timeout: function () {
//setTimeout(함수, 시간)
setTimeout( () => {
console.log(this.name);
}, 2000);
}
}
timer.timeout();
결과
Heropy!! // timer.timeout();의 결과