일반 함수 (function)은 자신의 this를 가짐:
const obj = {
name: "JS",
normalFunc: function () {
return this.name;
}
};
console.log(obj.normalFunc()); // 👉 "JS"
여기서 this는 obj를 가리킴.
화살표 함수는 자기 스코프의 this를 무시하고 상위 스코프의 this를 그대로 씀:
const obj = {
name: "JS",
arrowFunc: () => {
return this.name;
}
};
console.log(obj.arrowFunc()); // 👉 undefined (전역의 this.name)
this는 obj가 아니라 함수가 선언된 곳의 this (여기선 전역)
함수 종류 | this는 어디서 오나? | 특징 |
---|---|---|
function | 호출하는 대상 | 동적으로 결정됨 |
arrow | 정의된 위치의 스코프 | 렉시컬(정적)하게 바인딩됨 |
❗ arrow function은 this를 캡처(상속)하고, 일반 function은 this를 생성한다!