Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass class method as function argument while maintaining this context [duplicate]

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?

like image 862
Daskus Avatar asked Sep 16 '25 12:09

Daskus


1 Answers

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));
like image 73
Will Taylor Avatar answered Sep 19 '25 03:09

Will Taylor