For a library I'm writing I need the ability to use a method reference of a class instance as a callback function. To set the correct this
reference I would need to have to use arrow functions in the referenced class, which I'd like to avoid as that conflicts with method overloading. For a test I have this code (playground):
class Show {
private i = 42;
public show1(prefix: string): void {
console.log(prefix + " The answer is " + this.i);
}
public show2 = (prefix: string): void => {
console.log(prefix + " The answer is " + this.i);
}
}
class Test {
public showAll(show: (prefix: string) => void): void {
show("Test ");
}
}
const show = new Show();
const test = new Test();
test.showAll(show.show1.bind(show, "abc"));
test.showAll(show.show2);
Even though I use a class instance for the method reference, I still have to explicitly bind the this pointer, which makes this kinda inconvenient, especially, when you don't know the parameters. Additionally, the bind call removes all type information of the referenced method (returns any
), which is another blocking stone.
I would expect that a method reference of an actual class instance should automatically pick that instance, yet it does not. What other methods exist to avoid the bind call and arrow functions for correct the correct this
context in a method references?