类和属性问题

时间:2011-09-04 17:51:22

标签: javascript scope

我想在我的Android上使用地理定位API。我知道有一个“导航器”对象已定义,应该用于获取用户位置。所以,我创建了这个示例代码:

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调用onSuccess时,都没有定义this.locations字段(并且它刚好在new Array之后定义)。我知道我做错了,但因为这是我的JavaScript尝试之一,不知道是什么。那么,任何人都可以在这里找到问题吗?

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

导致您使用this。这将改变因为它取决于你的函数调用的上下文。只需使用函数的范围来声明位置:

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/

的内容

答案 2 :(得分:0)

尝试像这样定义onSuccess

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