Skip to content Skip to sidebar Skip to footer

How The Does Scope Differ Between These Three Ways Of Listening For Events?

Assuming the function doSomething() is defined in the same place, does the function's scope when it is executed differ between these three methods of listening for events?

Solution 1:

onload="doSomething();" is similar to

document.body.onload = function(event) { 
    doSomething();
};

Inside the event handler itself, this refers to the element the handler is bound to, but inside doSomething, this will refer to window, since you are calling the function "normally". doSomething doesn't have access to the event object either. You have to pass this and event along if you want doSomething work the same as in the other cases:

onload="doSomething.call(this, event);"

Note: Properties of document, ancestor DOM elements and the DOM element itself are in the scope for the event handler (not doSomething), which can lead to very confusing behavior. See my answer here for more info.

document.body.onload = doSomething; and document.body.addEventListener('load', doSomething); are equivalent in terms of scope and context, and they don't have this strange scope behavior that inline event handlers have.

More information about the different ways can be found on quirksmode.org.

Post a Comment for "How The Does Scope Differ Between These Three Ways Of Listening For Events?"