我有一个如下的函数。
我正在尝试调用它
var testVar = new genericYiiLocation();
console.log(testVar.getLongitude());
但是,我的 this.getLongitude() 总是有一个空的 this.longitude。
我已检查 this.longitude 是否包含在locateSuccess(loc) 中设置时预期的值,看起来没问题。
如有任何指导,我们将不胜感激。
function genericYiiLocation() {
console.log('genericYiiLocation: Creating location handler');
this.longitude= '';
this.latitude= '';
this.accuracy= '';
if (Modernizr.geolocation) {
console.log('genericYiiLocation: Location supported');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locateSuccess, locateFail);
}
else {
alert('genericYiiLocation: Geolocation is not supported in your current browser.');
return false;
}
} else {
alert ('genericYiiLocation: no native location support');
return false;
}
function locateSuccess(loc){
console.log('genericYiiLocation: storing location data');
this.longitude = loc.coords.longitude;
}
// Unsuccessful geolocation
function locateFail(geoPositionError) {
switch (geoPositionError.code) {
case 0: // UNKNOWN_ERROR
alert('An unknown error occurred, sorry');
break;
case 1: // PERMISSION_DENIED
alert('Permission to use Geolocation was denied');
break;
case 2: // POSITION_UNAVAILABLE
alert('Couldn\'t find you...');
break;
case 3: // TIMEOUT
alert('The Geolocation request took too long and timed out');
break;
default:
}
}
this.getLongitude = function(){
console.log('long: '+this.longitude);
return this.longitude;
}
}
最佳答案
据我了解原因是:
this
在你的回调中locateSuccess
与 this
不同在回调之外。为了实现你想要的,你可以绑定(bind)回调 localSuccess
& locateFail
至this
使用Function.prototype.bind
.
关于javascript - 调用javascript函数时变量为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14300700/