2011-09-04 67 views
1

我想在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字段没有被定义(并且它在新数组之后被定义)。我知道我做错了什么,但是因为它是我的一个JavaScript尝试,所以不知道是什么。那么,任何人都可以在这里找到问题?

回答

3

问题出在this的范围。当调用onSuccessonError时,this未绑定到包含locations数组的对象。您需要创建到该阵列均应分配的职能明确的变量外,然后在回调使用这个变量,像这样:

var allLocations = this.locations = [a, b, c]; 
this.onSuccess = function(position) { 
    alert("allLocations: " + allLocations); 
    alert("this.locations: " + this.locations); 
} 
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/

0

尝试定义onSuccess这样的:

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