Javascript : 匿名函数,访问全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19168440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript : Anonymous function, access to global variables
提问by Viot Camille
After hours of search, I Have a problem with my code Below. In fact, I'm not very far from answer I think but I'm still blocked…
经过数小时的搜索,我的代码出现问题。事实上,我离我想的答案不远了,但我仍然被阻止......
I have an anonymous function called inside a loop and I want to access and refresh global variables but I tried with window.myvariable, with another function and nothing happen…
我有一个在循环内调用的匿名函数,我想访问和刷新全局变量,但我尝试使用 window.myvariable 和另一个函数,但没有任何反应……
this my code :
这是我的代码:
for (var i = 0; i < SHP_files.length; i++) {
shapefile = new Shapefile({
shp: "shp/polygon/"+SHP_files[i]+".shp",
dbf: "shp/polygon/"+SHP_files[i]+".dbf",
}, function(data) {
polygon_layer.addLayer(new L.GeoJSON(data.geojson,{onEachFeature: onEachFeature, style: polygonStyle}));
polygon_layer.addTo(map);
console.log(polygon_layer.getLayers()); // IS OK
});
};
console.log(polygon_layer.getLayers()); // IS EMPTY !!
So, How i could transform this anonymous function in order to have something that I can access from my code who's following that ?
那么,我如何转换这个匿名函数,以便我可以从我的代码中访问一些东西?
Thanks a lot, and sorry for my english not very good…
非常感谢,很抱歉我的英语不是很好......
采纳答案by Steve
This is your typical problem with asynchronous code execution. You example code does NOT execute from top to bottom. In particular, your anonymous function does NOT get executed until Shapefileis done with whatever it is doing. In the meantime, your JS gets executed in order. Therefore, the last line of your above code, will probablyexecute before the anonymous function ever will.
这是异步代码执行的典型问题。您的示例代码不会从上到下执行。特别是,您的匿名函数在Shapefile完成它正在执行的任何操作之前不会执行。同时,您的 JS 会按顺序执行。因此,上面代码的最后一行可能会在匿名函数之前执行。
To fix this, you will need to trigger any code that depends on the Shapefileresponse from within its callback:
要解决此问题,您需要触发任何依赖Shapefile于其回调中的响应的代码:
for (var i = 0; i < SHP_files.length; i++) {
shapefile = new Shapefile({
shp: "shp/polygon/"+SHP_files[i]+".shp",
dbf: "shp/polygon/"+SHP_files[i]+".dbf",
}, function(data) {
polygon_layer.addLayer(new L.GeoJSON(data.geojson,{onEachFeature: onEachFeature, style: polygonStyle}));
polygon_layer.addTo(map);
executeMoreCode();
});
};
function executeMoreCode() {
console.log(polygon_layer.getLayers()); // IS OK
}
回答by Bryan Corey
Try defining your variables, in this case polygon_layer, outside of the for loop or the function. See the following example:
尝试在 for 循环或函数之外定义变量,在本例中为polygon_layer。请参阅以下示例:
var f;
for(var i=0; i<5;i++){
(function(){
f = 10;
console.log(f); // Outputs 10
})();
}
console.log(f); // Also outputs 10

![JavaScript:空数组,[ ] 在条件结构中计算为真。为什么是这样?](/res/img/loading.gif)