2013-07-02 5 views
1

나는과 같이, 응용 프로그램에서 나중에 사용할 수있는 객체에 현재의 위도와 경도를 추가 위치 정보를 사용하려고 해요 :자바 스크립트 객체 속성

var loc = { 
    get_latlong: function() { 
     var self = this, 
      update_loc = function(position) { 
       self.latitude = position.coords.latitude; 
       self.longitude = position.coords.longitude; 
      }; 

     win.navigator.geolocation.getCurrentPosition(update_loc); 
    } 
} 

내가 볼 수 그때 console.log(loc)loc.get_latlong()을 실행하면 개체, 메서드 및 콘솔의 두 속성

그러나 console.log(loc.latitude) 또는 console.log(loc.longitude)을 시도하면 정의되지 않습니다.

그게 전부에요?

+3

모든 당신이 JS에서 처리되는 방법을 _asynchronous_ 방법을 모르고 관하여 - 그래서 그 주제에 대한 몇 가지 연구를하시기 바랍니다. – CBroe

답변

2

다른 언급했듯이 비동기 호출 결과가 즉시 발생한다고 기대할 수 없기 때문에 콜백을 사용해야합니다. 이런 식으로 뭔가 :

var loc = { 
    get_latlong: function (callback) { 
     var self = this, 
      update_loc = function (position) { 
       self.latitude = position.coords.latitude; 
       self.longitude = position.coords.longitude; 
       callback(self); 
      } 

     win.navigator.geolocation.getCurrentPosition(update_loc); 
    } 
} 

는 다음 사용하여 전화 :

loc.get_latlong(function(loc) { 
    console.log(loc.latitude); 
    console.log(loc.longitude); 
}); 
+0

고마워요 @ 올렉, 그 트릭을 했어. –