JavaScript对象属性未定义

JavaScript对象属性未定义,javascript,object,geolocation,Javascript,Object,Geolocation,我正在尝试使用地理位置将当前纬度和经度添加到我稍后可以在应用程序中使用的对象,如下所示: var loc = { get_latlong: function() { var self = this, update_loc = function(position) { self.latitude = position.coords.latitude; self.longitude

我正在尝试使用地理位置将当前纬度和经度添加到我稍后可以在应用程序中使用的对象,如下所示:

    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)
时,它是未定义的


这是怎么回事?

正如其他人提到的,您不能期望异步调用的结果立即出现,您需要使用回调。大概是这样的:

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);
});

这都是关于你不知道如何在JS中处理异步方法的问题——所以请对这个主题做一些研究。