JavaScript에서
this키워드는 함수 호출 방식에 따라 동적으로 결정되며,
call,apply,bind는 이this값을 명시적으로 설정하는 데 사용된다.
this란 무엇인가?this는 함수가 호출될 때 해당 함수가 속한 객체를 참조하는 키워드이다.
호출 방식에 따라 this가 달라지며, 다음과 같은 패턴으로 나뉜다.
function show() {
console.log(this);
}
show(); // 브라우저: window, Node.js: global
this는 window (또는 Node.js에서는 global)를 가리킨다.const obj = {
name: 'JS',
say() {
console.log(this.name);
},
};
obj.say(); // 'JS'
this는 obj를 가리킨다.thisclass User {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hi, I'm ${this.name}`);
}
}
const user = new User('Alice');
user.greet(); // Hi, I'm Alice
thisconst button = document.querySelector('button');
button.addEventListener('click', function () {
console.log(this); // 클릭된 button 요소
});
this가 이벤트 대상(Element)을 가리킨다.this를 캡처한다.call, apply, bind이들 메서드는 모두 함수를 호출하거나 새로운 함수를 반환하면서 this를 지정할 수 있게 해준다.
call함수를 호출하면서 this를 명시적으로 지정한다.
function greet() {
console.log(`Hello, I'm ${this.name}`);
}
const person = { name: 'Alice' };
greet.call(person); // Hello, I'm Alice
추가 인자가 있다면 ,로 나열하면 된다.
function introduce(age) {
console.log(`${this.name} is ${age} years old`);
}
introduce.call(person, 25); // Alice is 25 years old
applycall과 유사하지만, 인자를 배열로 받는다.
introduce.apply(person, [30]); // Alice is 30 years old
apply는 call과 동일하게 this를 지정하지만, 인자를 배열 형태로 전달한다.bindcall, apply와 달리 함수를 즉시 실행하지 않고, this가 바인딩된 새로운 함수를 반환한다.
const boundFunc = greet.bind(person);
boundFunc(); // Hello, I'm Alice
인자도 사전에 고정 가능하다.
const boundIntroduce = introduce.bind(person, 40);
boundIntroduce(); // Alice is 40 years old
this화살표 함수는 자신의 this를 가지지 않고, 외부 스코프의 this를 캡처한다.
const obj = {
name: 'Bob',
greet: () => {
console.log(this.name);
}
};
obj.greet(); // undefined (전역 객체의 name)
this가 사라짐const person = {
name: 'Tom',
greet() {
console.log(this.name);
},
};
const fn = person.greet;
fn(); // undefined
const fnArrow = () => person.greet();
fnArrow(); // Tom
→ 해결: bind로 고정하거나 call, apply로 호출.
| 상황 | 추천 메서드 |
|---|---|
함수 실행 시 this 지정 | call / apply |
| 함수 실행을 나중에 하고 싶을 때 | bind |
| 인자 배열로 전달 필요 | apply |
this 유지가 필요한 이벤트 등 | bind |
이처럼 상황에 따라 적절한 메서드를 선택하면 this와 관련된 오류를 줄이고, 더욱 명확한 코드를 작성할 수 있다.