I was reading the MDN documentation on this in DOM event handlers which states:
When a function is used as an event handler, its
this
parameter is bound to the DOM element on which the listener is placed.
However, in practice this seems to be slightly misleading, because the listener’s this
is actually bound to whatever EventTarget
you attached it to—even if it isn’t an HTML element. For example:
// 'document' is not an Element node, but an EventTarget
document.addEventListener('visibilitychange', function() {
// `this` === document
console.log(this.hidden, document.hidden); // both true/false
});
Here, inside the handler, this.hidden
behaves exactly like document.hidden
. Similarly, if I do:
window.addEventListener('resize', function() {
console.log(this === window); // true
});
…the same principle applies: this
is the EventTarget
(in this case, window
), not necessarily a DOM Element
.
- Is the MDN wording inaccurate or just informal?
- What is the precise specification language for what
this
refers to in an event listener callback? - Should MDN’s phrasing be updated to mention “EventTarget” rather than “DOM element”?
Before I edit the MDN article, I need to make sure it really needs improvement.
Any references to the DOM/EventTarget spec or other authoritative sources would be greatly appreciated!