Прошу помочь с решением проблемы с this
Как сделать так. чтобы не было таких вызовов как: weather.getRequest(link) и прочее, а было например this.getRequest(link)
Спасибо заранее за ваши ответы! 'use strict' var weather = { id: 0, showWeather: function() { var target = { latitude: 0, longitude: 0 }; function getPosition(position) { var crd = position.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { navigator.geolocation.clearWatch(id) } var link = 'http://api.openweathermap.org/data/2.5/weather?lat=' + crd.latitude + '&lon=' + crd.longitude + '&units=metric&lang=ru&appid=b231606340553d9174136f7f083904b3'; weather.getRequest(link); } return this.id = navigator.geolocation.watchPosition(getPosition); }, getRequest: function(link) { var request = new XMLHttpRequest(); request.open('GET', link , true) request.onreadystatechange = function(e) { if (this.readyState == 4) { if(this.status == 200) { var response = JSON.parse(this.responseText); console.log(response); weather.showWeatherData(response); } } } request.send(null); }, showWeatherData: function(response) { var temp = response.main.temp; var hum = response.main.humidity; var descrpt = response.weather[0].description; temperature.innerHTML = temp; humidity.innerHTML = hum; description.innerHTML = descrpt; }, showCityWeather: function() { function getPosition() { var cityName = choiseCityName.value; var link = 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&units=metric&lang=ru&appid=b231606340553d9174136f7f083904b3'; weather.getRequest(link); } navigator.geolocation.clearWatch(this.id) console.log(this.id) return this.id = navigator.geolocation.watchPosition(getPosition); } } |
Цитата:
например в 10 строке можно заменить функцию на стрелочную, у нее нет своего контекста и она возьмет контекст weather, после этого можно вызвать внутри функции this.getRequest(link); getPosition =(position)=> { var crd = position.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { navigator.geolocation.clearWatch(id) } var link = 'http://api.openweathermap.org/data/2.5/weather?lat=' + crd.latitude + '&lon=' + crd.longitude + '&units=metric&lang=ru&appid=b231606340553d9174136f7f083904b3'; this.getRequest(link); }; |
Цитата:
Я все сделал так, но консоль ругается script1.js:10 Uncaught ReferenceError: getPosition is not defined UPD: Нужно было просто через var объявить и все заработало |
А как в этом куске избавиться от weather?
getRequest: function(link) { var request = new XMLHttpRequest(); request.open('GET', link , true) request.onreadystatechange = function(e) { if (this.readyState == 4) { if(this.status == 200) { var response = JSON.parse(this.responseText); console.log(response); weather.showWeatherData(response); } } } request.send(null); }, |
getRequest: function(link) { var $this = this; var request = new XMLHttpRequest(); request.open('GET', link , true) request.onreadystatechange = function(e) { if (this.readyState == 4) { if(this.status == 200) { var response = JSON.parse(this.responseText); console.log(response); $this.showWeatherData(response); } } } request.send(null); }, так например |
Спасибо. А можете дать какие-нибудь рекомендации по написанию кода. Т.е оценить этот
|
Artem_Andreev,
Переменных лишних много, если значение используется один раз, то нет смысла его сохранять в переменную. Запрос по городу вообще не зависит от геолокации, поэтому нет смысла getPosition в showCityWeather. Также не понятно зачем target в showWeather, если нет нужды стремиться к определенному местоположению. |
Часовой пояс GMT +3, время: 11:15. |