如何在 JavaScript 中实现该函数的闭包?
昨晚,我用谷歌搜索了很多,但找不到解决我的问题的方法: 我有一个 for 循环,其中有一个函数,它只获取数组中的最新值。
所以,这是一个例子:
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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它应该如下所示:
在此,我们将当前的
g
作为不同的变量传递到该自执行函数中,而不是在函数中共享的g
您当前所处的位置(这不是块作用域)并且正在更改for
循环的每一次传递。另请注意
for
循环更改...您永远不应该使用for...in
循环来迭代数组,请使用普通的 < code>for 循环。It should look like this:
In this we're passing the current
g
into that self-executing function as a different variable, rather than theg
which is shared in the function you're currently in (this isn't block scope) and is changing each pass of thefor
loop.Also note the
for
loop change...you should never use afor...in
loop to iterate an Array, use a normalfor
loop for that.