【发布时间】:2016-08-07 15:35:47
【问题描述】:
我正在使用 Google 地图集成制作一个网站。下面是一些显示布局的示例代码以及我遇到问题的地方,我认为它与范围相关,但无法弄清楚。 Maps API 调用 initMap() 一旦使用 API 加载到必须在 initMap 中执行的任何内容,但我还需要 obj 作为全局变量,以便在 initMap() 完成后可以访问并执行操作。
var obj = {};
var initMap = function() {
obj = {
"map": null,
"locations": null,
"refreshStuff": function() {
// Do things to populate all the null values
// i.e.
obj.locations = [0,1,2,3,4,5];
alert(/*message to show values are what they should be*/); // They are
},
"otherThings": "otherThings"
};
obj.refreshStuff();
alert(/*message to check values are still what they should be*/); // They're null
};
alert(/*message to check values are still what they should be*/); // They're null
obj 的 null 属性一旦在设置它们的函数之外恢复为 null 是否有原因?
编辑 1
成员变量并不总是恢复为 null,它们会恢复为最初的状态,我最初只是为所有这些变量使用 null。
obj = {
"location_ex1": null,
"location_ex2": 0
};
alert(obj.location_ex1); // null
alert(obj.location_ex1); // 0
编辑 2
这是一个未正确设置值的函数的完整代码 sn-p
obj = {
// ...
"userLocationFirstRun": true,
"refreshUserLocation": function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
obj.userLocation.position = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
if (obj.userLocationFirstRun) {
obj.userLocationFirstRun = false;
obj.userLocation.marker = new google.maps.Marker({
map: obj.map,
position: obj.userLocation.position,
draggable: false,
icon: { url: "/images/location_marker.png" }
});
}
alert(JSON.stringify(obj.userLocation.position)); // <-- Correct coords
}, function() {
//Geolocation error - Service failed
alert("Geolocation service failed");
});
}
else {
//Geolocation error - No geolocation ability
alert("Geolocation service not available");
}
},
"userLocation": {
"marker": null,
"position": null,
}
// ...
};
obj.refreshUserLocation();
alert(JSON.stringify(obj.userLocation.position)); // <-- null
【问题讨论】:
-
refreshStuff是否进行任何异步函数调用?如果您提供 minimal reproducible example 而不是到处放置 cmets 会更好。 -
里面有Ajax来加载位置数据,但它不仅仅是通过Ajax加载的数据设置的东西。我有通过 HTML5 导航器加载的用户位置坐标等项目也恢复为 null。到目前为止,从成员函数中设置的任何成员变量,无论我可能正在设置它,都将恢复为 null。
-
我刚刚对其进行了测试,它们本身并没有恢复为 null,而是恢复为成员变量声明中设置为默认值的值。即 "locations": null 返回 null 和 "locations": 0 retuens 0
-
你能再显示一些代码吗?一旦您调用
initMap(),所有由refreshStuff设置的变量都将显示为非空值。
标签: javascript json google-maps-api-3