topical media & game development
#javascript-code-16-scope.js / js
// An element with an ID of main
var obj = document.getElementById("main");
// An array of items to bind to
var items = [ "click", "keypress" ];
// Iterate through each of the items
for ( var i = 0; i < items.length; i++ ) {
// Use a self-executed anonymous function to induce scope
(function(){
// Bind a function to the elment
obj[ "on" + items[i] ] = function() {
// items[i] refers to a parent variable that has been successfully
// scoped within the context of this for loop
alert( "Thanks for your " + items[i] );
};
})();
}
(C) Æliens
20/2/2008
You may not copy or print any of this material without explicit permission of the author or the publisher.
In case of other copyright issues, contact the author.