I was trying to find the meaning of this
keyword inside event handler function in the DOM level 3 event spec.
As per my experiment this
refers to the event.currentTarget
object.
Is this behavior mentioned somewhere in the standard?
As per "JavaScript The Definitive Guide" book this
refers to the event target
which seems to wrong. event.currentTarget
seems more logical as event handlers are invoked as the method of the HTML element object.
Can someone please clarify?
In case of bubbling I see "this" changes and means the event.currentTarget.
In an event handler for an element, with default capturing (false), this
will refer to the element which detected the event. Either one may be used.
For example:
element.addEventListener('keydown', function (event) {
// `this` will point to `element`
}, false);
When capturing an event (true), say at the window level, event.target
, will refer to the element which originated the event, while this
will refer to the capturing element. For example:
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 exemplifies the difference between each.
Indeed, the Definitive Guide is wrong in that case.
I found a reference in the HTML5 event handler processing algorithm:
Invoke
callback
with one argument, the value of which is the Event objectE
, with the callback this value set toE
'scurrentTarget
.
The DOM level 3 event specification didn't say much about it in previous versions - it was meant to be language agnostic. The Appendix F: ECMAScript Language Binding just stated
EventListener function: This function has no return value. The parameter shall be an object that implements the
Event
interface.
However, current versions omitted these bindings. And in its Glossary appendix event listeners are described:
event handler, event listener: An object that implements the
EventListener
interface and provides anEventListener.handleEvent()
callback method. Event handlers are language-specific. Event handlers are invoked in the context of a particular object (the current event target) and are provided with theevent
object itself.
Also, the upcoming DOM Level 4 draft, whose goals contain aligning the DOM with the needs of EcmaScript, does explicitly state in the Dispatching Events section:
If
listener
's callback is a Function object, its callback this value is theevent
'scurrentTarget
attribute value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With