I'm trying to pass a class method to Array.map. Instead of doing Array.map(v => this.classMethod(v)) I want to just pass the method like Array.map(this.classMethod). But this does not work.
The problem is that if classMethod tries to access a member variable an error is thrown, as this seems to have the wrong context.
class Foo {
    private memberVariable: number = 42;
    public bar(){
        return [1,2,3].map(this.classMethod);
    }
    private classMethod(v: number){
        return this.memberVariable * v;
    }
}
console.log(new Foo().bar()); // Throws TypeError: this is undefined
Is there a way to pass a class method to a function and still maintain the right this context inside the passed method?
You could define classMethod as an arrow function:
private classMethod = (v: number) => {
    return this.memberVariable * v;
}
Alternatively leave classMethod as it is, and then the caller of the function can use bind to specify the this context:
[1,2,3].map(this.classMethod.bind(this));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With