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?