简体   繁体   English

明确分配后在Javascript中未定义变量?

[英]Variable Undefined in Javascript after Explicit Assignment?

For some reason my "initialLocation" variable is undefined when I make an alert on it, even though I explicitly assign it in the callback function for getCurrentPosition. 出于某种原因,即使我在getCurrentPosition的回调函数中显式分配了变量,但对它发出警报时我的“ initialLocation”变量却未定义。 Variable "initialLocation" is declared globally btw. 全局声明变量“ initialLocation”。

Maybe I'm not understanding this concept of closures? 也许我不了解这种封闭的概念?

var initialLocation;

if (navigator.geolocation) {
    geoLocationError = true;
    navigator.geolocation.getCurrentPosition(function(position) {
        initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
        getFood();
        }, geoError);
    alert(initialLocation);
} else {
    geoLocationError = false;
    noGeolocation(geoLocationError);
}

navigator.geolocation.getCurrentPosition is asynchronous, so your alert is firing before initialLocation is set. navigator.geolocation.getCurrentPosition是异步的,因此在设置initialLocation之前会触发您的警报。 You should place your alert inside the callback, just after you set initialLocation . 在设置initialLocation之后,应将警报放置在回调中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM