Skip to content Skip to sidebar Skip to footer

Why Can't I Roll A Loop In Javascript?

I am working on a web page that uses dojo and has a number (6 in my test case, but variable in general) of project widgets on it. I'm invoking dojo.addOnLoad(init), and in my init

Solution 1:

this is a common problem when dealing with closures. try this:

for (var i = 0; i < 6; i++) {
    (function(i){
      dojo.connect(dijit.byId("project" + i).InputNode, "onChange",  function()   {makeMatch(i);});
    }(i));
}

Solution 2:

i is a local variable inside the for loop. When the onChange function is called, all 6 functions have a reference to i, which is 6.

It's the same problem as #4 on Jon Skeet's C# Brainteaser's page

List<Printer> printers = new List<Printer>();
for (int i=0; i < 10; i++)
{
    printers.Add(delegate { Console.WriteLine(i); });
}

foreach (Printer printer in printers)
{
    printer();
}

which prints all 10's

Post a Comment for "Why Can't I Roll A Loop In Javascript?"