Javascript-форум (https://javascript.ru/forum/)
-   Events/DOM/Window (https://javascript.ru/forum/events/)
-   -   Прошу помочь с решением проблемы с this (https://javascript.ru/forum/events/74923-proshu-pomoch-s-resheniem-problemy-s.html)

Artem_Andreev 16.08.2018 23:37

Прошу помочь с решением проблемы с 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);
  }
}

j0hnik 17.08.2018 00:04

Цитата:

Сообщение от Artem_Andreev
чтобы не было таких вызовов как: weather.getRequest(link)

вызывать в подходящем контексте
например в 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);
       };

Artem_Andreev 17.08.2018 08:41

Цитата:

Сообщение от j0hnik (Сообщение 492937)
вызывать в подходящем контексте
например в 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 объявить и все заработало

Artem_Andreev 17.08.2018 08:48

А как в этом куске избавиться от 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);
  },

j0hnik 17.08.2018 08:56

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 17.08.2018 15:54

Спасибо. А можете дать какие-нибудь рекомендации по написанию кода. Т.е оценить этот

Rise 17.08.2018 21:33

Artem_Andreev,
Переменных лишних много, если значение используется один раз, то нет смысла его сохранять в переменную. Запрос по городу вообще не зависит от геолокации, поэтому нет смысла getPosition в showCityWeather. Также не понятно зачем target в showWeather, если нет нужды стремиться к определенному местоположению.


Часовой пояс GMT +3, время: 11:15.