Typescript solution 2+
TL; DR : Typescript Playground , "Repo with Demo"
Benefits:
- Check compilation time.
- It will not allow you to lose
this context if you pass an instance method. - Do not lose performance: you do not need to declare class methods as instance methods (for example,
public somefunc = () => { return this.prop; } ) - More .... - Do not mess with the class prototype.
- Agreed signature template: passing the callback as the first arg and
thisArg as the second (e.g. Array.prototype.map () ).
Consider the following code:
class Foo { private result: number = 42; public func(this: Foo): number { return this.result; } } function action(): void { console.log("Hello world!"); } function bar(callbackFn: (this: void) => any, thisArg?: undefined): any; function bar<T>(callbackFn: (this: T) => any, thisArg: T): any; function bar<T, TResult>(callbackFn: (this: T) => TResult, thisArg: T): TResult { return callbackFn.call(thisArg); } const foo = new Foo(); bar(action);
Turn your attention to the signature Foo#func :
public func(this: Foo): number
Indicates that this function should be called in the context of the class instance. This is the first part of the solution that will not let you lose this context.
The second part is the function overload bar :
function bar(callbackFn: (this: void) => any, thisArg?: undefined): any; function bar<T>(callbackFn: (this: T) => any, thisArg: T): any; function bar<T, TResult>(callbackFn: (this: T) => TResult, thisArg: T): TResult
This will allow you to pass common functions as well as instance methods.
You can learn more about these topics in the TypeScript Reference:
Deilan Sep 16 '17 at 17:09 on 2017-09-16 17:09
source share