我把JS范围搞混了。我试图将值分配给坐标并在以后使用它们,但由于某种原因,我总是将坐标设为null。
var thing = (function($){
var obj = function(config) {
$.extend(obj.config, config);
obj.init();
};
$.extend(obj, {
coordinates: {},
browser_geolocation: function() {
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
obj.browser_coordinates, //set coordinates
maps.browser_error,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
},
browser_coordinates: function(position) {
obj.coordinates.long = position.coords.longitude;
obj.coordinates.lat = position.coords.latitude;
},
});
$(function() {
maps.browser_geolocation();
maps.browser_geolocation();
console.log(obj.coordinates);
});
return obj;
}(jQuery));
我似乎无法弄清楚我做错了什么?
答案 0 :(得分:1)
这里有两个主要问题:
您可能希望在JavaScript中研究原型继承,它并不像它看起来那么难。
以下是如何创建使用回调的可自定义对象的示例:
function GetCoordinates(callback) {
var successCallback = function (position) {
this.coordinates = position.coords;
callback();
};
var errorCallback = function (error) {
throw error;
};
var self = this;
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(function () {
successCallback.apply(self, arguments)
}, errorCallback, {
enableHighAccuracy: true,
timeout: timeoutVal,
maximumAge: 0
});
}
}
(function() {
// callback to execute once coordinates are ready
var myCallback = function() {
console.log(c.coordinates); // Coordinates
};
// create object (don't forget new :))
var c = new GetCoordinates(myCallback);
// because geolocation.getCurrentPosition is async, the following will be undefined
console.log(typeof c.coordinates);
}());