bind 메서드

정혜인·2024년 8월 3일
0

javascript

목록 보기
5/9

💨 bind 메서드

💡 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 함수의 thisobj로 고정하여, boundLogValue를 호출할 때 thisobj를 참조하게 만들어줌

⭕ 내 코드

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)LooperprocessFunction으로 전달되고, Looper가 호출할 때도 checkQueuethisManager 인스턴스를 참조하게 만들어줌. 이렇게 하지 않으면 checkQueue 메서드 내의 thisManager 인스턴스가 아닌, 호출된 컨텍스트를 참조하게 되어 오류 발생.

0개의 댓글