Darko Martic
Darko Martic

Reputation: 219

How to implement a closure for this function in JavaScript?

Last night, I Googled a lot and couldn't find the solution for my problem: I have a for loop with one function in it which gets me only the latest value from the array.

So, here is the example:

obj1.route = new Routeng();
obj2.route = new Routeng();

for(var x in arrObjs) { //arrObjs = array of objects
  var g = arrObjs[x];

  // I can access properties of all "g" objects

  Routelousse.gen(function(res) {
    var pathern = res.pathern;
    g.routel.staviPather(pathern);

    MYOBJ.vehicles.push(g);
    alert(g.name); // during the loop I always get the LAST "g" object from "arrObjs"
  }, g.point);

}

Upvotes: 1

Views: 139

Answers (1)

Nick Craver
Nick Craver

Reputation: 630419

It should look like this:

obj1.route = new Routeng();
obj2.route = new Routeng();

for(var x=0; x<arrObjs.length; x++) {
  var g = arrObjs[x];

  (function(ig) {
    Routelousse.gen(function(res) {
      var pathern = res.pathern;
      ig.routel.staviPather(pathern);

      MYOBJ.vehicles.push(ig);
      alert(ig.name);
    }, ig.point);
  })(g);
}

In this we're passing the current g into that self-executing function as a different variable, rather than the g which is shared in the function you're currently in (this isn't block scope) and is changing each pass of the for loop.

Also note the for loop change...you should never use a for...in loop to iterate an Array, use a normal for loop for that.

Upvotes: 2

Related Questions