JavaScript对象属性未定义

时间:2013-07-02 22:33:40

标签: javascript object geolocation

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

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

这是怎么回事?

1 个答案:

答案 0 :(得分: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);
});