Just to add. I remember asking similar questions on here years ago and struggling to wrap my head around the answers given. I seem to remember call and apply being offered at the time.
When you pass a handler function to addEventListener e.g.
document.addEventListener('click', handlerFunction)
The handlerFunction is saved to be run at a later time.
So for instance 10 seconds after the page is loaded, when you perform a mouse click the handler function will be called and an event object will be passed to it as an argument.
However if you do the following
document.addEventListener('click', handlerFunction(x, y))
Due to the use of the parentheses the handler function is being called immediately. The only thing being saved by addEventListener for later is what ever handlerFunction returns and that could quite possibly be undefined.
To illustrate you could make that function return another function
function getHandlerFunction() {
// return a handler function to the addEventListener
return function(event) {
console.log(event.type) // click
}
}
document.addEventListener('click', getHandlerFunction())
getHandlerFunction is called immeditately and returns the inner function
function(event) {
console.log(event.type) // click
}
This is the function that will be assigned to the eventListener, and could actually just be typed in as
document.addEventListener('click', function(event) {
console.log(event.type) // click
})