我在我的 JavaScript 对象属性中获得未定义的值

i am getting undefined value in my javascript object property

本文关键字:未定义 属性 我的 JavaScript 对象      更新时间:2023-09-26

我有一个代码笔,基本上从OpenWeather中获取值,并尝试根据应用程序状态对其进行设置。我似乎无法弄清楚为什么我得到一个未定义的this.tempValuethis.tempType值。代码如下:

'

var app = {
  latitude: '',
  longitude: '',
  tempType : " C",
  tempValue: "",
  getGeoLoc: function (id) {
      //Removed timeout option due to error
      var options = {}; //{ timeout: 3 };
      navigator.geolocation.getCurrentPosition(this.foundLoc.bind(this), this.noloc, options);
  },
  foundLoc : function(position) {
    this.latitude = position.coords.latitude;
    this.longitude = position.coords.longitude; 
    console.log('coords ', this.latitude, this.longitude);
    // Call your get weather function
    // Using call to bind the context of `this`
    this.getWather.call(this);
  },
  // Error method
  noloc: function(err) {
     console.log(err.message);
  },
  // Method to get your weather after location is found
  getWather: function() {
      var url = 'http://api.openweathermap.org/data/2.5/weather?lat=' + this.latitude + '&lon='  + this.longitude +'&APPID=7bda183adf213c8cfa2ef68635588ef3';
      console.log('URL is: '+url);
      $.getJSON(url, function(data) {
        console.log('Your weather data', data);
        // Do your dom stuff here
       $("#location").text(data.name); 
        console.log("#5 does this work??? ", data.main.temp.toString().slice(0, 2));
        var temp = '';
        this.tempValue = data.main.temp.toString().slice(0, 2);
        var type = "";
        type = this.tempType;
        console.log("#6 what's inside tempType. ", this.tempType);
        $("#temp").html(this.tempValue + this.tempType);
        $("#message").html(data.weather[0].description);
        console.log("#3 what is in the description property. ", data.weather[0].description);
        //function to convert C to F and vice versa and return a string
        function convert (value) {
         var celsius = '';
          var fahrenheit = '';
          var convertedToF = 0;
          var convertedToC = 0;
          if(value == 'fahrenheit') {
        convertedToF =   data.main.temp *  9/5 + 32;
            this.tempValue = convertedToF;
           console.log("#4 fahrenheit value is ", convertedToF); 
          }
          if(value == 'celsius') {
            convertedToC = data.main.temp  -  32;
            convertedToC *=  5/9;
            this.tempValue = convertedToC;
          }
        }
        $("#convert").click( function () {
          convert('celsius');
        }
        );

      });
  },

};
// Make sure to call your initialising function
app.getGeoLoc();

Codepen URL 是: http://codepen.io/rush86999/pen/MKMywE/?editors=1010

getJSON的成功callBack中,this对象将指向jqXHR object(如@dfsq所述)。这就是为什么你看到这两个变量undefined。有不同的方法可用于解决此问题。其中之一是,

$.getJSON(url, function(data) { 
 // ...YOUR CODE...
}.bind(this));