obj['e'+type+fn]( window.event );
The use of the "obj[...]" notation is not limited to arrays in JavaScript; it can be applied to any object as well. In this particular case, Resig is adding a property to various objects, specifically targeting DOM objects.
Using obj['aVar']
is essentially the same as using obj.aVar
, but with added flexibility. The former allows for the handling of reserved keywords and dynamic access to property names, such as demonstrated with the type
variable example. Trying to access obj.type
directly wouldn't yield the desired result because it would search for a property named exactly "type," rather than one matching the value of the type
variable.
Objects and arrays can store functions as data, enabling the invocation of a function within an object or array by specifying its property followed by parentheses (as shown here) with arguments like window.event
. Additionally, functions have a default toString
method on their prototype, helpful for cases requiring string concatenation while maintaining function integrity unless the user specifies a custom toString
method on the function itself.
Resig's approach involves defining a new property somewhat haphazardly, but implemented in a way that minimizes potential conflicts with other applications. For instance, assigning the values "click" to the type
variable and function () {alert('boo!');}
to fn
results in naming a property on document.body
identified as "eloadfunction () {alert('boo!');}". By creating and invoking this property within his anonymous function, Resig ensures consistent behavior when utilizing the "this" keyword—it defaults to referencing the parent object (obj
), avoiding global references unless obj
represents the global context (i.e., the window
object).