0

I wrote a program where something like this occurs :

class MyClass 
{
    att: number = 0

    private exec(f: () => void ) {
        f()
    }

    private increment() { 
        this.att += 1
    }

    public do(): number {
        this.exec(this.increment)
        return this.att
    }

}

let a = new MyClass()
console.log(a.do()) // prints 0

What is the prettiest way to transfer the "this" with the function in parameters

Pylvain
  • 56
  • 1
  • 5
  • 1
    See [How to access the correct `this` inside a callback?](https://stackoverflow.com/q/20279484) and [How does the “this” keyword work?](https://stackoverflow.com/q/3127429). You can probably do `this.exec(this.increment.bind(this))` but I'm not a big fan of it due to the redundant sandwich syntax of placing `this` on both sides. It's probably more conventional as `this.exec(() => this.increment())`. – VLAZ Dec 01 '20 at 19:21
  • 1
    You could also do `f.call(this);`, but yeah, I opt for `this.exec(() => this.increment())` as well. – David Sherret Dec 01 '20 at 19:22

1 Answers1

0

There's a ton of ways to solve this. I'll share 3 approaches:

this.exec(this.increment.bind(this));
this.exec(() => this.increment());

Or, define increment itself as an arrow function, which is a style I've seen often in React class components:

private increment = () => { 
    this.att += 1
}
Evert
  • 75,014
  • 17
  • 95
  • 156