When a callback runs in response to an event, this
inside the function is set to the DOM element that is the target of the event.
In your first example, the anonymous function gets the this
of the target element, but that this
is not forwarded to the inner function call. Instead, the inner function runs with a this
according to how it is invoked. (Here, it's a direct "raw" call (i.e., not called as a member function), so it runs with a this
equal to window
, in non-script mode.)
In your second example, the functions update_percentage
and show_hide_targets
get the this
of the target element directly.
Consider an example:
function sayThis() { alert(this); }
someElem.addEventListener("click", function() { sayThis() });
someElem.addEventListener("click", sayThis);
someElem.addEventListener("click", function() { sayThis.call(this) });
The first will alert window
(or undefined
in strict mode); the second will alert the element the listener fired on. The third listener uses an anonymous function, but it invokes the inner function using .call(this)
, which forwards the original this
to the inner function.