0

In a typescript project I have an utility function that should 'wrap' some behavior. Similar to:

const methodWrapper = (cb: () => void): void => {
    console.log("Wrapped:before");
    cb();
    console.log("Wrapped:after");
}

When passing an instance method as parameter, this get lost and is undefined.

class Foo {
    constructor(private val: string) { }

    private logVal() { console.log(this.val); }

    public test() {
        methodWrapper(this.logVal);
    }
}

const f = new Foo("myVal");
f.test(); // Fail because this is undefined

Is there a way to setup my utility function to preserve the this value ?

As a workaround, I can pass the value as an arrow function like this:

class Foo {
    constructor(private val: string) { }

    private logVal() { console.log(this.val); }

    public test() {
        methodWrapper(() => this.logVal()); // Works as expected
    }
}

Or by setting explicitly the this value:

class Foo {
    constructor(private val: string) { }

    private logVal() { console.log(this.val); }

    public test() {
        methodWrapper(this.logVal.bind(this));
    }
}

These workarounds require, however, extra syntax I'd like to avoid.

Full repro: Playground Link

Steve B
  • 36,818
  • 21
  • 101
  • 174

0 Answers0