this 키워드와 바인딩 (The 'this' Keyword)
자바스크립트의 this는 다른 언어와 달리 "함수가 어떻게 호출되었는가"에 따라 동적으로 결정됩니다. 화살표 함수는 이 룰을 무시하고 무조건 상위 환경의 this를 물려받습니다.
const user = {
name: "Alice",
// 1. 일반 메서드 (메서드를 호출한 객체가 this가 됨)
sayHi: function() {
console.log(`안녕, 나는 ${this.name}`);
},
// 2. 화살표 함수 (자신만의 this가 없어서 밖의 this를 가져옴)
sayHiArrow: () => {
// 여기서의 this는 전역 객체(window/global)를 가리킴
console.log(`안녕, 나는 ${this.name}`);
}
};
user.sayHi(); // "안녕, 나는 Alice"
user.sayHiArrow(); // "안녕, 나는 undefined"
// 3. this 바인딩을 강제하는 메서드 (call, apply, bind)
function introduce(greeting) {
console.log(`${greeting}, 나는 ${this.name}`);
}
const otherUser = { name: "Bob" };
// 첫 번째 인자로 this가 될 객체를 넘겨줌
introduce.call(otherUser, "반가워"); // "반가워, 나는 Bob"
// bind는 호출하지 않고 this가 묶인 '새로운 함수'를 반환함
const boundFunc = introduce.bind(otherUser);
boundFunc("안녕"); // "안녕, 나는 Bob"