// 일반 함수는 호출 위치에 따라 this 정의
// 화살표 함수는 자신이 선언된 함수 범위에서 this 정의
const malza = {
name: 'Malza',
normal: function () {
console.log(this.name); // Malza
},
arrow: () => {
console.log(this.name); // undefined
},
};
malza.normal();
malza.arrow();
const amy = {
name: 'Amy',
normal: malza.normal,
arrow: malza.arrow,
};
amy.normal(); // Amy
amy.arrow(); // undefined. malza 에서 this 가 정해지기 때문에 amy 와 전혀 상관없다.
const timer = {
name: 'Malza',
timeout: function () {
setTimeout(function () {
console.log(this.name);
}, 2000);
},
};
timer.timeout(); // 아무것도 안나온다. 현재 this는 일반 함수로 호출 위치에서 정의된다.
// 따라서 setTimeout 함수의 내부 로직으로 cb 되서 call 되기때문에 알 수 없다.
const timer = {
name: 'Malza',
timeout: function () {
setTimeout(() => {
console.log(this.name);
}, 2000);
},
};
timer.timeout(); // Malza.
// 화살표 함수를 timeout 이라는 일반 함수가 감싸고 있다. 그리고 해당 함수는 timer 를 가리킨다.
// 따라서 Malza 가 나온다.