자바스크립트의 this는 함수 호출 방식에 따라 동적으로 바인딩되는 자기 참조 변수입니다. 이는 자바나 C++ 같은 클래스 기반 언어에서 this가 항상 클래스의 인스턴스를 가리키는 것과 다릅니다. 함수가 어떻게 호출되느냐에 따라 this가 가리키는 대상이 달라지며, strict mode(엄격 모드) 역시 이 바인딩에 영향을 미칩니다.
this바인딩은 함수가 호출된 방식에 따라 동적으로 결정됩니다..
this는 전역 객체를 가리킵니다. 브라우저에서는 window, Node.js에서는 global 객체가 이에 해당합니다.this가 undefined로 바인딩됩니다.function() {
console.log(this);
}
foo() // 브라우저에서는 window, Node.js에서는 global
this는 해당 메서드를 소유하고 있는 객체에 바인딩됩니다.const person = {
name: 'Ju',
getName() {
return this.name;
}
};
console.log(person.getName()); // Ju
this는 생성된 인스턴스에 바인딩됩니다. 이는 클래스 기반 객체 지향 언어의 this와 유사하게 동작합니다.function Circle(radius) {
this.radius = radius;
this.getDiameter = function() {
return 2 * this.radius;
};
}
const circle = new Circle(5)
console.log(circle.getDiameter()); // 10
ES6의 클래스 문법으로 생성자를 만들 수도 있습니다
class Circle {
constructor(radius) {
this.radius = radius;
}
getDiameter() {
return 2 * this.radius;
}
}
const circle = new Circle(5);
console.log(circle.getDiameter()); // 10
apply와 call 메서드는 함수를 호출하면서 첫 번째 인자로 전달된 값을 this로 바인딩합니다.bind는 첫 번째 인자로 전달된 값을 this로 바인딩한 새로운 함수를 반환합니다.function greet() {
console.log(`Hello, ${this.name}`);
}
const user = { name: 'Ju' };
greet.call(user); // Hello, Ju
greet.apply(user); // Hello, Ju
const greetUser = greet.bind(user);
greetUser(); // Hello, Ju
지금까지 함수 호출 방식에 따라 this 바인딩이 동적으로 결정되는 것에 대해 살펴보았습니다. 이를 정리해 보면 다음과 같습니다.
| 함수 호출 방식 | this 바인딩 |
|---|---|
| 일반 함수 호출 | 전역 객체 |
| 메서드 호출 | 메서드를 호출한 객체 |
| 생성자 함수 호출 | 생성자 함수가 (미래에) 생성할 인스턴스 |
| apply/call/bind | 메서드레 첫 번째 인수로 전달한 객체 |
✅ 참고
치피치피 차파차파 루비루비 라바라바