⛔️ function vs arrow function의 차이
✅ example
const obj = {
name: "Javascript",
getThis: function () {
return this;
},
getThisArrow: () => {
return this;
}
};
console.log(obj.getThis().name);
console.log(obj.getThisArrow().name);
🧠 핵심 개념: this의 차이
방식 | this가 가리키는 대상 |
---|
function 키워드 | 호출한 객체 (obj) |
arrow function | 상위 스코프의 this (lexical this) — 여기선 전역 |
🔍 분석
1. obj.getThis()
getThis: function() {
return this;
}
- 이 메서드는 일반 함수 (function)로 선언됨
- 호출 시: obj.getThis() → this는 obj를 가리킴 ✅
- 따라서 this.name → "Javascript"
console.log(obj.getThis().name);
2. obj.getThisArrow()
getThisArrow: () => {
return this;
}
- 화살표 함수는 this를 자신이 선언된 스코프의 this로 고정
- 여기서 this는 obj가 아니라 전역 객체 (window in 브라우저, global in Node.js)
- 전역 객체에는 name 속성이 없기 때문에:
console.log(obj.getThisArrow().name);
✅ 최종 출력
Javascript
undefined
📌 요약
메서드 | this |
---|
getThis() | obj |
getThisArrow() | 전역 |
💡 팁
- 화살표 함수는 메서드로 쓰지 마세요.
- this가 객체를 가리키게 하려면 반드시 function 키워드를 써야 합니다.