Magnus
Magnus

Reputation: 7833

Event Listener's Parameters

TypeScript's type definition file for ES6 (lib.es6.d.ts), defines addEventListener on the window object as follows:

addEventListener<K extends keyof WindowEventMap>(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;

As seen, it defines the listener as having two parameters: this and ev.

As we know, ev is the event object and this is the DOM element the event was fired from. We also know that the browser automatically passes these arguments into the event listener when the event fires.

Question

When I create a handler and check the length of its arguments, I am told there is only one:

window.addEventListener('keydown', myHandler2);

function myHandler2() {
    // Output of the below is: args length: 1, arg 1: [object KeyboardEvent]
    console.log('args length: ' + arguments.length + ', arg 1: ' + arguments[0]);
}

Thus, I am wondering, why is the method definition telling me there are two parameters, when in fact there is only one?

Side Note

This is not specific to addEventListener. The onclick method, for example, has the following type-definition:

onclick: (this: HTMLElement, ev: MouseEvent) => any;

Upvotes: 2

Views: 1596

Answers (2)

Alan
Alan

Reputation: 593

Per the Typescript docs on functions:

[When declaring a function,] you can provide an explicit this parameter. this parameters are fake parameters that come first in the parameter list of a function.

Note the description of this as a "fake" parameter. In JavaScript, this is an implicit parameter for functions. Its value is determined by how the function is called, and it cannot be provided as a positional argument when calling a function. TypeScript works around this by pretending that it is the first positional argument (hence calling it "fake").

If you are unfamiliar with this in JavaScript functions, you may find it valuable to read Understanding JavaScript Function Invocation and "this".

Upvotes: 1

Eamonn McEvoy
Eamonn McEvoy

Reputation: 8986

this doesn't show in the argument list as it is not really a parameter, just a reference to the calling object. In the event listener example this refers to the window object.

this parameters are fake parameters that come first in the parameter list of a function:

https://www.typescriptlang.org/docs/handbook/functions.html

Upvotes: 1

Related Questions