Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

closures

Status
Not open for further replies.

slobad23

IS-IT--Management
Jun 30, 2006
90
GB
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!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top