Home > Software design >  Use this as parameter name in javascript function definition
Use this as parameter name in javascript function definition

Time:06-30

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

CodePudding user response:

Paraphrasing the typescript documentation on this

Declaring this in a Function

TypeScript will infer what this should be in a function via code flow analysis

But, there are a lot of cases where you need more control over what object this represents. Since the JavaScript specification states that you cannot have a parameter called this, TypeScript uses that syntax space to let you declare the type for this in 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

  • Related