Why is the parameter needed for keydown events?

Why is it necessary to add a parameter to handle events? For instance:

  document.addEventListener( 'keydown', function( e ) {
                        var keyCode = e.keyCode } );

Why do you need it e? ' ' why does a function need a parameter at all?

+4
source share
3 answers

edenotes an event object that contains information about the activated event (type of event, key code, purpose of the event, etc.). This object is passed to the handler function when an event is triggered.

It's not obligatory. If you don’t care which key is pressed or any other event information, just skip this option.

, . arguments[0], . .

+2

:

Event , .

, .

function foo(evt) {
  // the evt parameter is automatically assigned the event object
  alert(evt);
}
table_el.onclick = foo;

:

H E :

1.    H.

2. NULL, .

3. E :

E - ErrorEvent, IDL - OnErrorEventHandler

, E-, E filename, - E lineno, - E colno, E, E currentTarget. . [WEBIDL]

, E, , E currentTarget. . [WEBIDL]

.

4. :

- , E ErrorEvent

Web IDL, . beforeunload

IDL - OnBeforeUnloadEventHandler, null DOMString.

null, .

E BeforeUnloadEvent, E , returnValue .

Web IDL, .

+2

.. ( )

There are times when you want to know which element caused the event and what the event is. And more information .. In your example, e.keycodeit is useful to determine which key was pressed.

There are many methods in this argument, such as preventDefault()to prevent the behavior of the default event or e.targetto get the target that triggered the event. Therefore, you need to pass the argument e as a parameter to the function.

If you do not require it, just do not pass it as an argument

0
source

Source: https://habr.com/ru/post/1568943/