Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use this as parameter name in javascript function definition

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading