My knowledge of closures is far from at an advanced level, but it is my understanding that the anonymous function defined, when referencing a local variable defined within the same scope of that function, holds the value of that variable, despite what may affect said variable later.
This would leave me to believe, that in this code, the value alerted when each form field triggers it's onblur should be different (goHandle and go2Handle respectively):
var formBean = {
"formString": "Demo",
"formFields":[
{
"name":"go",
"id":"go",
"validationString":"myTest"
},
{
"name":"go2",
"id":"go2",
"validationString":"myTest2"
}
]
};
window.onload = function()
{
for(var i=0;i<formBean.formFields.length;i++) {
var field = formBean.formFields[i];
var fieldMethod = field.name + "Handle";
document.getElementById(field.id).onblur = function() {
alert(fieldMethod);
};
}
}
<input type="text" id="go" />
<input type="text" id="go2" />
However, what happens is, whichever field you leave, thus triggering the onblur, the second value alerts, suggestion the closure is not a closure at all, but it simply using the current value of the variable.
You can observe this behavior in this fiddle:
Could someone please explain what I've done wrong or misunderstood about closures? And why this isn't working the way I expect. Thank-you very much.