2013-07-02 83 views
1

我試圖使用地理位置到當前的經緯度添加到一個目標,我可以在一個應用程序以後使用,就像這樣:未定義JavaScript對象的屬性

var loc = { 
    get_latlong: function() { 
     var self = this, 
      update_loc = function(position) { 
       self.latitude = position.coords.latitude; 
       self.longitude = position.coords.longitude; 
      }; 

     win.navigator.geolocation.getCurrentPosition(update_loc); 
    } 
} 

當我運行loc.get_latlong()然後console.log(loc)我可以看到控制檯中的對象,方法和兩個屬性。

但是,當我嘗試console.log(loc.latitude)console.log(loc.longitude)它是未定義的。

這是什麼意思?

+3

這是所有關於你不知道如何_asynchronous_方法在JS進行處理 - 所以請不要在該主題的一些研究。 – CBroe

回答

2

正如其他人所說,你不能期望異步調用立即來臨的結果,你需要使用回調。事情是這樣的:

var loc = { 
    get_latlong: function (callback) { 
     var self = this, 
      update_loc = function (position) { 
       self.latitude = position.coords.latitude; 
       self.longitude = position.coords.longitude; 
       callback(self); 
      } 

     win.navigator.geolocation.getCurrentPosition(update_loc); 
    } 
} 

然後調用它使用:

loc.get_latlong(function(loc) { 
    console.log(loc.latitude); 
    console.log(loc.longitude); 
}); 
+0

謝謝@奧列格,那就是訣竅。 –