The below example was taken from the book, “Javascript: The good parts”. The author says that the helper function returns a function that binds to the current value of var i.
Can anyone explain what makes it to bind the VALUE instead of REFERENCE of var i, because helper function is a closure to add_the_handler function and should only see the reference of var i:
var add_the_handlers = function (nodes) {
var helper = function (i) {
return function (e) {
alert(i);
};
};
var i;
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = helper(i);
}
};
If you were to say:
The function would not have it’s own copy of
ibecauseiis not declared within the scope of the function.To help you see this better I’ve modified your above code:
In the “real world” you’ll often see code like the above shortened to look like this: