Please, consider the following code.
Question
When the code is called from an on-event handler, its this
is set to the DOM element on which the listener is placed:
Note however that only the outer code has its this set this way. In this case, the inner function's this
isn't set so it returns the global/window object (i.e. the default object in non–strict
mode where this
isn't set by the call).
Check this
in the global context and in function context.
Another consideration is when you use addEventListener
.
Check event listener with an anonymous function and with an arrow function and this
in arrow functions.
Please note that while anonymous and arrow functions are similar, they have different this
bindings. While anonymous (and all traditional JavaScript functions) create their own this bindings, arrow functions inherit the this binding of the containing context.
Here is a simple article I wrote about the JavaScript this keyword but it doesn't mention event handler.