Is it possible to avoid scope binding in NodeJs?

11 Views Asked by At

I often need my callback functions to act on the object that triggered them, which translate to this kind of code :

class MyClass {
    constructor() {
        this.on('whatever', this.doSomething.bind(this);
    }

    doSomething(event){
        this.doSomethingElse();
    }

    doSomethingElse(){
        // Stuff
    }
}

But I can't help but think there must be a better way to keep the scope in the callback (avoiding an undefined this), other than using .bind(this) on every single callback in my code. Any idea would be appreciated !

0

There are 0 best solutions below