this 바인딩의 차이점

rada·2025년 4월 6일
0

개발

목록 보기
38/43

⛔️ 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); // ✅ "Javascript"

2. obj.getThisArrow()

getThisArrow: () => {
  return this;
}
  • 화살표 함수는 this를 자신이 선언된 스코프의 this로 고정
  • 여기서 this는 obj가 아니라 전역 객체 (window in 브라우저, global in Node.js)
  • 전역 객체에는 name 속성이 없기 때문에:
console.log(obj.getThisArrow().name); // ❌ undefined

✅ 최종 출력

Javascript
undefined

📌 요약

메서드this
getThis()obj
getThisArrow()전역

💡 팁

  • 화살표 함수는 메서드로 쓰지 마세요.
  • this가 객체를 가리키게 하려면 반드시 function 키워드를 써야 합니다.
profile
So that my future self will not be ashamed of myself.

0개의 댓글