Event handler scope (Definition)

The scope of an event handler is somewhat different to the normal scope.

Although event handlers are functions like any other, they are not called from global code and therefore are running in a different scope chain context to that which your functions normally execute.

The head of the scope chain is the call object. Arguments passed to the event handler are available here as they would be in other function calls.

In a normal context, the next object in the scope chain might be the global object. However for the event handler, it is the object to which the event was directed. This makes event handles somewhat easier to write.

For example, the form object yielded in the scope for an event handler attached to an <INPUT> tag is the form object that the FormElement object belongs to. This scope chain continues up the document hierarchy (the DOM), until it reaches the global object. You can share various parts of the form handling code by plugging it into objects at different points in the DOM.

The scope chain for an <INPUT> object is the reverse of its DOM location. Thus:

window.document.form.button.event

will seek to resolve its identifiers in this order:

Warnings:

See also:Document, Element.onevent, Function scope, Function.call()