2011-09-04 86 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);