can someone please explain the following to me:
//It's important to understand that the inner function has access to the actual
//variables of the outer functions and not copies in order to acoid the
//following problem
//BAD EXAMPLE
//Make a function that assigns event handler functions to an array of nodes the
//wrong way. When you click 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.onclick = function (e) {
alert(i);
};
}
};
//END BAD EXAMPLE
//The add_the_handlers function was intended to give each handler a unique
//number i. It fails because the handler functions are bound to the variable i,
//not the value of the variable i at the time the function was made.
//BETTER EXAMPLE
//Make a function that assigns event handler functions to an array of nodes.
//When you click on a node, an alert box will display the ordinal of the node.
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.onclick = helper(i);
}
};
I have tried logging this, and I can't see what it wrong with the BAD EXAMPLE.
Thanks!
//It's important to understand that the inner function has access to the actual
//variables of the outer functions and not copies in order to acoid the
//following problem
//BAD EXAMPLE
//Make a function that assigns event handler functions to an array of nodes the
//wrong way. When you click 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.onclick = function (e) {
alert(i);
};
}
};
//END BAD EXAMPLE
//The add_the_handlers function was intended to give each handler a unique
//number i. It fails because the handler functions are bound to the variable i,
//not the value of the variable i at the time the function was made.
//BETTER EXAMPLE
//Make a function that assigns event handler functions to an array of nodes.
//When you click on a node, an alert box will display the ordinal of the node.
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.onclick = helper(i);
}
};
I have tried logging this, and I can't see what it wrong with the BAD EXAMPLE.
Thanks!