💡 this를 자신이 지정한 객체에 바인딩하도록 해주는 역할
(함수의this
값을 고정할 수 있게 해줌)
function bindFunction(func, context) {
return func.bind(context);
}
class MyClass {
constructor() {
this.value = 42;
}
logValue() {
console.log(this.value);
}
}
const obj = new MyClass();
const boundLogValue = obj.logValue.bind(obj);
boundLogValue(); // 42, `this`가 MyClass 인스턴스를 참조
위의 코드에서 obj.logValue.bind(obj)
는 logValue
함수의 this
를 obj
로 고정하여, boundLogValue
를 호출할 때 this
가 obj
를 참조하게 만들어줌
class Manager {
constructor(queueManager) {
this.queueManager = queueManager;
this.looper = new Looper(this.checkQueue.bind(this), 1000); // `checkQueue`의 `this`를 `Manager` 인스턴스에 바인딩
}
async checkQueue() {
// ...
}
}
여기서 this.checkQueue.bind(this)
는 Looper
의 processFunction
으로 전달되고, Looper
가 호출할 때도 checkQueue
의 this
가 Manager
인스턴스를 참조하게 만들어줌. 이렇게 하지 않으면 checkQueue
메서드 내의 this
가 Manager
인스턴스가 아닌, 호출된 컨텍스트를 참조하게 되어 오류 발생.