0

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 !

dododingo
  • 79
  • 7
  • Use class field arrow functions instead. `doSomething = (event) => {` – CertainPerformance Jun 18 '22 at 15:30
  • You could also do `this.on('whatever', () => this.doSomething())` but it's strictly a matter of taste of which is preferred. Neither is better or worse than the other – slebetman Jun 18 '22 at 18:15
  • Another option is to permanently bind `this` in the constructor. At the beginning of the constructor, before doing anything else do this: `this.doSomething = this.doSomething.bind(this); this.doSomethingElse = this.doSomethingElse.bind(this)` etc. until all your methods are permanently bound. However, if you do this you are breaking inheritance. But in a lot of modern OO inheritance is either rarely used or **never** used preferring composition instead – slebetman Jun 18 '22 at 18:18

0 Answers0