2016-03-02 64 views
1

我有一個codepen,基本上從openweather中獲取價值,並嘗試根據應用程序狀態進行設置。我似乎無法弄清楚爲什麼我得到一個未定義的值爲this.tempValuethis.tempType。下面的代碼:我在我的JavaScript對象屬性中獲取undefined值

`

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網址是:http://codepen.io/rush86999/pen/MKMywE/?editors=1010

回答

2

成功的getJSONcallBack裏面,this目標將指向jqXHR object(由@dfsq提到)。這就是爲什麼你看到undefined這兩個變量。有不同的方法可以解決這個問題。其中一個會是,

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

它不會指向'window',但你說得對,上下文會有所不同。 – dfsq

+0

@dfsq在文檔中找到並更新相同。感謝您指出它。 –

+0

請注意,在其他情況下,您可能無法獲得像這樣的綁定函數,您可以使用經典var me = this; .... me.tempValue – Walfrat