I'm currently learning javascript from the following book 'JavaScript: The Good Parts - O'Reilly Media', which says the following:
It is important to understand that the inner function has access to the actual variables of the outer functions and not copies in order to avoid the following problem:
// BAD EXAMPLE
// Make a function that assigns event handler functions to an array of nodes the
wrong way.
// When you click on a node, an alert box is supposed to display the ordinal of the
node.
// But it always displays the number of nodes instead.
var add_the_handlers = function (nodes)
{
var i;
for (i = 0; i < nodes.length; i += 1)
{
nodes[i].onclick = function (e)
{
alert(i);
};
}
};
// END BAD EXAMPLE
Question: I don't understand what the problem is, if someone could give me a clear example with numbers and results that would greatly be appreciated.