1.MDN example
The code snippet below assign a function that display the help text to each text field when focus, here is the link to JsFiddle: https://jsfiddle.net/v7gjv/8164/
function showHelp(help) {
document.getElementById('help').textContent = help;
}
function setupHelp() {
var helpText = [
{'id': 'email', 'help': 'Your e-mail address'},
{'id': 'name', 'help': 'Your full name'},
{'id': 'age', 'help': 'Your age (you must be over 16)'}
];
for (var i = 0; i < helpText.length; i++) {
var item = helpText[i];
document.getElementById(item.id).onfocus = function() {
showHelp(item.help);
}
}
}
setupHelp();
But it will only display the last help text no matter which of the three input is focused. MDN says the function assigned to all three inputs is a closure, so they share the same reference to variable helpText, when the loop's over, i=2, so all three input have reference to the last item in helpText.
2.My test
The part where i dont understand is why all three inputs have the same reference to the same variable item I make a test like this
(function() {
function closure() {
var i = 0;
return {
display: function() {
console.log(i);
},
add: function() {
i += 1;
}
}
}
var a = closure();
var b = closure();
a.add();
a.display(); //return 1
b.display(); //return 0
})()
3.My thoughts and questions
From the test, a and b have different i variables, i from a changed but b remain the same. But in the for loop, all inputs point to the same variable, thus the for loop change the value i causing all inputs point to the last item in helpText
So my question is why do they points to the same variable but in my test a,b don't.
In your example, you're declaring the variable i inside the closure method. When you are calling closure a second time, a new i variable is created in the scope of that specific function execution, and the returned object is bound to that variable.
Try moving the variable declaration outside of the closure function and you will see that the result is the same as the MDN example.