• 0
  • 2
March 10, 2025

자바스크립트의 this 바인딩

답변 확인

  • 자바스크립트에서 this는 함수가 호출되는 방식에 따라 바인딩되는 객체가 달라집니다.

📌 1. 전역 호출(Global Context)

  • 전역에서 this는 전역 객체를 가리김
    • 브라우저 환경 -> window
    • Node.js 환경 -> global
function globalFunc() {
  console.log(this);
}
globalFunc(); // 브라우저: window, Node.js: global

📌 2.메서드 호출(Object Method)

  • 객체의 메서드에서 this는 해당 객체를 참조
const obj = {
  name: 'Alice',
  greet: function () {
    console.log(this.name);
  },
};
obj.greet(); // "Alice"

📌 3.생성자 함수와 클래스(Constructor & Class)

  • 생성자 함수 또는 클래스에서 this는 새로운 인스턴스(객체)를 참조
function Person(name) {
  this.name = name;
}
const person = new Person('Alice');
console.log(person.name); // "Alice"

📌 4. 명시적 바인딩 (Call, apply, blind)

  • call(), apply(), bind()를 사용하면 this를 명시적으로 설정 가능
function greet() {
  console.log(this.name);
}
const user = { name: 'Alice' };
 
greet.call(user); // "Alice" (this를 user로 설정)
greet.apply(user); // "Alice"
const boundGreet = greet.bind(user);
boundGreet(); // "Alice"

📌 5. 화살표 함수 (Arrow Function)

  • 화살표 함수는 자신만의 this를 가지지 않음
  • 따라서 상위 스코프의 this를 상속받음
const obj = {
  name: 'Alice',
  greet: () => console.log(this.name),
};
obj.greet(); // undefined (전역 `this`)
 
const obj2 = {
  name: 'Alice',
  greet: function () {
    const inner = () => console.log(this.name);
    inner();
  },
};
obj2.greet(); // "Alice" (상위 스코프인 obj2의 this를 상속)

📌 6. DOM 이벤트 핸들러

  • 일반 함수: this는 이벤트가 발생한 요소 (event target)
  • 화살표 함수: 상위 스코프의 this를 상속받음
const button = document.querySelector('button');
 
button.addEventListener('click', function () {
  console.log(this); // 클릭된 button 요소
});
 
button.addEventListener('click', () => {
  console.log(this); // 화살표 함수 → 상위 스코프 (window)
});

🔹 결론

  • this는 함수 호출 방식에 따라 결정됨
  • ✔ 화살표 함수는 자신만의 this가 없고, 상위 스코프의 this를 상속
  • call(), apply(), bind()를 사용해 this를 명시적으로 설정 가능
  • this의 동작을 명확히 이해하고, 상황에 따라 적절한 방식으로 활용해야 함 🚀

📚 참고 자료

Top comments (2)

  • DavidYang2월 19일

    우와 댓글이다~

  • Olivia2월 19일

    오오 ~~ :) 너무 글 좋네용