[Javascript] Help with closures

Schuyler Ullman sullman at cs.stanford.edu
Fri Jan 12 13:03:08 CST 2007


Following up on what Roger said,

> The bottom line is: when you refer to a variable inside a closure
> that is set outside the closure, the variable contains its last
> value, not its value when the closure was created.  This usually only
> bites you when you are in a loop context like this.

This does not mean that all is lost. Each new call to a function that
creates a closure creates a new closure. This means that you can
create a helper function that will create the closure, and then call
the helper function from inside your loop. Consider the following
simplified example:

   var fns = [];

   function badTest()
   {
       var i;

       // This doesn't work because in all three functions
       // i has a value of three!

       for (i = 0; i < 3; i++)
       {
           fns[i] = function() { alert(i); };
       }
   }

   function goodTest()
   {
       var i;

       // This should work

       for (i = 0; i < 3; i++)
       {
           fns[i] = closureHelper(i);
       }
   }

   function closureHelper(i)
   {
       return function() { alert(i); };
   }

   function testFunctions()
   {
       var i;

       for (i = 0; i < fns.length; i++)
           fns[i]();
   }

Schuyler



More information about the Javascript mailing list