陷入javascript变量闭包

Stuck in javascript variables closures

本文关键字:闭包 变量 javascript 陷入      更新时间:2023-09-26

我只是想把position.coords.latitude和经度分配给lat和lon vars,但似乎我错过了一些东西,因为Console总是说lat-lon是未定义的。

function init() 
{
    var lat;
    var lon;
    if (navigator.geolocation) {
       navigator.geolocation.getCurrentPosition(function(position)
       {
          lat = position.coords.latitude;
          lon = position.coords.longitude;     
       });
    }
    console.log(lat);
    console.log(lon);
}

问题是,当您像最初那样使用var定义变量时,它们的值是未定义的。现在,当您调用getCurrentPosition函数时,它可能是异步的,这意味着console.logs在您实际分配任何值之前就被调用了。尝试以下更改

function init() 
{
    var lat;
    var lon;
    if (navigator.geolocation) {
       navigator.geolocation.getCurrentPosition(function(position)
       {
          lat = position.coords.latitude;
          lon = position.coords.longitude;  
          // Log them in the callback function
          console.log(lat);
          console.log(lon);  
       });
    }
}

由于您希望在拥有coords之后执行实际的代码,以下是如何更改init函数以适应异步体系结构的方法。

// New function argument callbackFn - the function to call after 
// coords are loaded
function init(callbackFn) 
{
    // Removed local variables, no need for them here
    if (navigator.geolocation) {
       navigator.geolocation.getCurrentPosition(function(position)
       {
          var lat = position.coords.latitude;
          var lon = position.coords.longitude;  
          // This will be logged after the async call completes, probably after 
          // the console.log call below
          console.log("finished async call");
          // Execute the callback with coords
          callbackFn(lat, lon);
       });
    }
    // This will be called as soon as JS steps over previous lines, 
    // but before the asynchronous request has completed
    console.log("finished init");
}

让我们假设当您执行一个名为start with latitude和经度的函数时,您的实际程序就开始了。在这种情况下,您将使用以下程序启动您的程序:

function start(latitude, longitude) {
    // ... SNIP ... DO SOMETHING COOL
}
init(start);

我想navigator.geolocation.getCurrentPosition()是异步的,所以在您尝试写入控制台时它不会执行。

尝试将控制台写入移动到回调函数中:

function init() 
{
    if (navigator.geolocation) {
       navigator.geolocation.getCurrentPosition(function(position)
       {
          var lat = position.coords.latitude;
          var lon = position.coords.longitude;   
          console.log(lat);
          console.log(lon);
       });
    }
}