开发者

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);

}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜