Using this inside an event handler

I tried to find the value of the this inside the event handler function in the DOM level event specification.

According to my experiment, this refers to the event.currentTarget object.

Is this behavior mentioned somewhere in the standard?

According to the “JavaScript Complete Guide”, this book refers to an event target , which seems incorrect. event.currentTarget seems more logical since event handlers are called as an object method of an HTML element.

Can anyone clarify?

In the case of bubbling, I see changes to "this" and means event.currentTarget.

+7
source share
2 answers

Indeed, in this case, the Complete Guide is incorrect.

I found a link in the HTML5 event handler processing algorithm :

Call a callback with one argument, whose value is an Event E object, with this value callback set to E currentTarget .

The DOM level 3 event specification in previous versions did not say anything about it - it should have been language independent. Appendix F: ECMAScript Language Binding Just Specified

EventListener Function : This function has no return value. The parameter must be an object that implements the Event interface.

However, in current versions, these bindings are omitted. And in the appendix to the Glossary , event listeners are described :

event handler, event listener : an object that implements the EventListener interface and provides the EventListener.handleEvent() callback method. Event handlers are language dependent. Event handlers are called in the context of a specific object (the current goal of the event ) and are supplied with the event object itself.

In addition, in the upcoming DOM Level 4 project, the goals of which include bringing the DOM in accordance with the needs of EcmaScript, it is explicitly indicated in the "Event Scheduling " section :

If listener callback is a Function object, its callback this value is the event currentTarget attribute value.

+11
source

In the event handler for an element with a default capture (false), this will refer to the element that detected the event. You can use any of them.

For instance:

 element.addEventListener('keydown', function (event) { // `this` will point to `element` }, false); 

When capturing an event (true), say, at the window level event.target , it will refer to the element that triggered the event, and this will refer to the capture element. For instance:

 window.addEventListener("error", function (event) { event.target.src = 'some_path'; // `this` will point to window // `event.target` will point to the element that had an error }, true); 

I hope this illustrates the difference between each.

+5
source

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


All Articles