Reputation: 559
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);
}
};
Upvotes: 3
Views: 2272
Reputation: 141927
If you were to say:
nodes[i].onclick = function(){ alert(i) };
The function would not have it's own copy of i
because i
is not declared within the scope of the function.
To help you see this better I've modified your above code:
var add_the_handlers = function (nodes) {
var helper = function(t) {
// t is in the scope of "helper"
return function(e){
// e is in the scope of this anonymous function
// and is not used
alert(t);
};
};
// Variables declared here are in the scope of "add_the_handlers"
var i;
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = helper(i);
}
};
In the "real world" you'll often see code like the above shortened to look like this:
var add_the_handlers = function(nodes){
var i;
for(i = 0; i < nodes.length; i++)
nodes[i].onclick = (function(i){ return function(e){ alert(i); }; })(i);
};
Upvotes: 5
Reputation:
You pass the current value of i
into the function helper
. Inside that function the variable i
, a (confusingly named) parameter to the function, is different from any other i
. The closure returned thus binds to that particular i
(really the [[scope]] which contains that i
, but...).
Happy coding.
Upvotes: 1
Reputation: 3080
This is a guess: i
is a primitive, so it's always accessed by value, and not by reference.
Upvotes: 0