so I'm understanding closures and circular references (I hope), but one aspect is the much reported closure within a loop which seems to cause much ado. I need clarification on it. The code I'm looking at is:
function showHelp(help) {
document.getElementById('help').innerHTML = help;
}
function getHelp(help) {
alert(help);
// only to show value of "help" at this point, also to prove that "getHelp()" is being called even
// though the onfocus wasn't used
return function() {
showHelp(help);
}
}
function setupHelp(){
var helpText = [
{'id':"email",'help':"Your email address"},
{'id':"name",'help':"Your full name"},
{'id':"age",'help':"Your real age"}
];
for(var i=0;i<helpText.length;i++){
var item = helpText[i];
alert(item.help);
// only to show value of "help" at this point, also to prove that "getHelp()" is
// being called even though the onfocus wasn't used
document.getElementById(item.id).onfocus = getHelp(item.help);
}
}
The premise here being that you have three input fields and focusing them will return a helpful hint (as seen on the MDC article). But, here's the crux of my lack of grasp: If you put an alert (so as to test) in the "getHelp()" function, and put one in the "setupHelp()" function, just before you set bind the event handler to a reference to the dom element, you'll see that, on loading the page, the loop runs, then the getHelp() function, then the loop, then the getHelp() function, etc, until the end of the loop. So if the getHelp() function is bound to the onfocus event handler, and you don't even focus the input fields, howe can the getHelp() function run?? And how does JAvaScript store all possible outcomes from that one little loop? :S
Any help you could provide would really help, this is mind boggling right now. I'm sure it'll just click one of these days, but I'm impatient. :P
Tom.