Issue
I saw a function definition like this in my learning vscode source code.
export function once<T extends Function>(this: unknown, fn: T): T {
const _this = this;
let didCall = false;
let result: unknown;
return function () {
if (didCall) {
return result;
}
didCall = true;
result = fn.apply(_this, arguments);
return result;
} as unknown as T;
}
But this argument is not passed when calling
... ...
const self = trackDisposable({
dispose: once(() => {
markAsDisposed(self);
fn();
})
});
... ...
I want to determine if javascript will automatically pass this argument in this case
Solution
Paraphrasing the typescript documentation on this
Declaring
thisin a FunctionTypeScript will infer what
thisshould be in a function via code flow analysisBut, there are a lot of cases where you need more control over what object
thisrepresents. Since the JavaScript specification states that you cannot have a parameter calledthis, TypeScript uses that syntax space to let you declare the type forthisin the function body.This is common with "callback-style" APIs, where another object typically controls when your function is called. Note that you need to use function, and not an arrow function, to get this behaviour
In other words
export function once<T extends Function>(this: unknown, fn: T): T {
simply defines that this will be unknown, but the function takes a single argument, fn : T
Answered By - Bravo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.