지도 클래스 작동하지 '이'범위 : mapObject.getUserPosition()
내가 this.userLatitude
및 this.userLongitude
을 점검 한 0을 반환하는 이유자바 스크립트 OOP
var mapObject = new Map();
console.log(mapObject.getUserPosition()); // Why does this return 0???
내가 알아낼 수 없습니다 : 개체 호출
function Map() {
this.map;
this.userLatitude = 0;
this.userLongitude = 0;
this.startPositionReporting();
}
Map.prototype.getUserPosition = function() {
alert(this.userLatitude);
return {
latitude: this.userLatitude,
longitude: this.userLongitude
};
};
Map.prototype.startPositionReporting = function() {
var geolocationOptions = {
enableHighAccuracy : true
};
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
this.userLatitude = position.coords.latitude;
this.userLongitude = position.coords.longitude;
}, null, geolocationOptions);
}
};
을 startPositionReporting
메서드 내부에 있으며 제대로 작동합니다. 이것은 범위와 관련이 있어야합니다 ... 어떤 아이디어입니까?
빠른 생각 ... 그것은 범위 문제처럼 보인다. 네비게이터 코드 앞에'var _this = this;'를 넣고 리턴 함수에서'this '를'_this'로 변경하십시오. –