2017-11-08 3 views
0

자바 스크립트 코딩에 대한 이전 절차 적 접근 방식에서 더 많은 객체 기반 접근 방식으로 이동하려고합니다.javascript 객체 변수 및 메서드 범위 문제 navigator.geolocation.watchPosition 사용

var gps = new geolocation(); 

function geolocation() { 
    this.watchID; 
    this.position; 

    this.success = function(p) { 
    this.position = p; 
    }; 

    this.failure = function(error) { 
    var errmsg; 

    // convert the error code to a readable message 
    switch(error.code) 
    { 
     case error.PERMISSION_DENIED: 
      errmsg="App doesn't have permission to access your location."; 
      break; 
     case error.POSITION_UNAVAILABLE: 
      errmsg="Your location information is unavailable to App."; 
      break;  
     case error.TIMEOUT: 
      errmsg="App's request to get your location timed out.";   
      break; 
     case error.UNKNOWN_ERROR: 
      errmsg="An unknown GPS error occurred."; 
      break; 
    } 
    console.log(errmsg); 
    }; 

    this.watchPosition = function() { 
    if(!this.watchID) 
    { 
     this.watchID = navigator.geolocation.watchPosition(this.success, this.failure, { maximumAge: 1000, timeout: 15000, enableHighAccuracy: true }); 
    } 
    }; 

    this.getPosition = function() { 
    return(this.position); 
    }; 

    this.clearWatch = function() { 
    if(this.watchID) 
    { 
     // turn off the watch 
     navigator.geolocation.clearWatch(this.watchID); 
     this.watchID = null; 
     console.log("GPS WatchID was cleared.", "GPS Status"); 
    } 
    }; 
}; 

나는이 객체의 모든 메소드에 액세스 할 수 있습니다 다음과 같이 내가 마이그레이션하기 위해 노력하고있어 코드의 조각 중 하나는 내 위치 추적기입니다. gps.watchPosition()을 시작할 때; this.watchID가 설정됩니다. 그러나, 내가 사용

var p = gps.getPosition(); 

내가 얻을 페이지 '정의되지 않은'디버거를 통해 실행하는 this.position도 정의되지 같이.

이 코드를 절차상의 상태로 되돌려도 잘 동작합니다. 분명히, 나는 무엇인가 놓치고있다. 그러나 나는 단지 무엇이 있는지에 관해 계산할 수 없다.

(참고 : 나는 게시하기 전에이 코드의 일부 최소화했다)

+0

나는'navigator.geolocation.watchPosition'이 완료 아니라고 추측에는 요 (이것은 비동기 호출의 오른쪽?) 당신이하는 getPosition를 호출 할 때. – James

+0

watchPosition은 init에서 호출됩니다 ... 나는 1 분 정도 기다렸다가 getPosition을 치고 같은 결과를 얻을 수 있습니다. 그리고 내가 말했듯이, 나는 이것을 절차 적으로 되돌릴 수 있으며 그것은 정상적으로 작동한다. – ppetree

답변

0

대답은 "이"에있다 -로 분명히 "이"자바 스크립트 엔지니어를위한 조금 너무 복잡하므로 내부와 유지하여 개체를 "this"의 복사본을 만든 다음 복사본을 사용하여 개체의 항목을 참조해야합니다.

function geolocation() { 
    var self = this; 
    this.watchID; 
    this.position; 

    this.success = function(p) { 
    self.position = p; 
    };