자바스크립트에서 this는 함수가 호출될 때 결정되며, 호출 문맥에 다라 다르게 바인딩이 된다. 일반적으로 this 바인딩 규칙은 다음과 같다.
function globalFunction() {
console.log(this); // 전역 객체 (브라우저에서는 window)
}
globalFunction();
const myObject = {
myMethod: function() {
console.log(this); // myObject
}
};
myObject.myMethod();
function MyClass() {
this.property = "Hello, this is a property.";
}
const myInstance = new MyClass();
console.log(myInstance.property); // Hello, this is a property.
const arrowFunction = () => {
console.log(this); // 외부 스코프의 this를 사용
};
arrowFunction.call({}); // 외부 스코프의 this를 사용
function explicitFunction() {
console.log(this);
}
const explicitObject = { name: "Explicit Object" };
explicitFunction.call(explicitObject); // explicitObject
여기서 함수 내부에서 call, apply, bind 메소드를 사용한 바인딩에 대해서 좀더 알아보고자 한다.
fun.call(thisArg, arg1, arg2, ...)
함수를 호출하면서 특정 객체를 thisArg로 설정하고 필요한 매개 변수를 전달한다.
fun.apply(thisArg, [argsArray])
함수를 호출하면서 특정 객체는 thisArg로 설정하고, 매개변수를 배열로 전달한다.
const newFunc = func.bind(thisArg, arg1, arg2, ...)
특정 객체를 thisArg로 설정하고, 필요한 매개 변수를 미치 바인딩한 새로운 함수를 생성한다.
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet.call(null, 'John'); // Hello, John!
greet.apply(null, ['Jane']); // Hello, Jane!
const greetJohn = greet.bind(null, 'John');
greetJohn(); // Hello, John!