类和属性问题

Class and attribute problem

本文关键字:问题 属性      更新时间:2023-09-26

我想在我的Android上玩地理定位API。我知道有一个已定义的"navigator"对象,它应该用于获取用户位置。因此,我创建了这个示例代码:

function GeolocationTester()
{
    // here I want to store all acquired locations
    this.locations = new Array();
    alert("this.locations defined: " + this.locations);
    this.onSuccess = function(position)
    {
        alert("Entered onSuccess");
        alert("this.locations defined: " + this.locations);
    }
    this.onError = function(error)
    {
        alert("error acquiring location");
    }
    navigator.geolocation.watchPosition(this.onSuccess, this.onError, { enableHighAccuracy: true });
}

这对我不起作用。每次watchPosition调用成功的这个。locations字段没有定义(它是在new Array之后定义的)。我知道我做错了什么,但因为这是我的JavaScript尝试之一,不确定什么。有人发现问题了吗?

问题在于this的范围。当调用onSuccessonError时,this不绑定到包含locations数组的对象。您需要在函数之外创建一个显式变量,数组应该分配给该变量,然后在回调中使用该变量,如下所示:

var allLocations = this.locations = [a, b, c];
this.onSuccess = function(position) {
    alert("allLocations: " + allLocations);
    alert("this.locations: " + this.locations);
}

这是你使用this的原因。这将会改变,因为它取决于你的函数调用的上下文。只需使用函数的作用域来声明location:

function GeolocationTester()
{
    // here I want to store all acquired locations
    var locations = [];
    alert("locations defined: " + locations);
    function onSuccess(position)    {
        alert("Entered onSuccess");
        alert("locations defined: " + locations);
    }
   function onError(error){
        alert("error acquiring location");
   }

 navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true });
}

要真正了解this,请阅读这篇博文http://dmitrysoshnikov.com/ecmascript/chapter-3-this/

尝试这样定义onSuccess:

this.onSuccess = (function(locations) {
    return function(position)
           {
               alert("Entered onSuccess");
               alert("this.locations defined: " + locations);
           }
})(this.locations);