如何保存函数调用之间的参数值?

问题描述:

我正试图创建一个天气应用程序,向OpenWeatherMap发送Ajax请求。我在w.getWeatherFunc中有一个错误,当我给函数sendRequest的w.weather的参数,然后给函数displayFunc,我接下来调用相同的参数。如何保存函数调用之间的参数值?

以下是我在控制台已经有了:

遗漏的类型错误:在displayFunc的不确定 无法读取属性 '天气'(weather.js:46) 在weather.js:78

我该如何解决这个问题并使其工作?

function Weather() { 
    var w = this; 

    var weatherUrl = 'http://api.openweathermap.org/data/2.5/weather?'; 
    var appid = '&appid=c0a7816b2acba9dbfb70977a1e537369'; 
    var googleUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='; 
    var googleKey = '&key=AIzaSyBHBjF5lDpw2tSXVJ6A1ra-RKT90ek5bvQ'; 

    w.demo = document.getElementById('demo'); 
    w.place = document.getElementById('place'); 
    w.description = document.getElementById('description'); 
    w.temp = document.getElementById('temp'); 
    w.humidity = document.getElementById('humidity'); 
    w.getWeather = document.getElementById('getWeather'); 
    w.addCityBtn = document.getElementById('addCity'); 
    w.rmCityBtn = document.getElementById('rmCity'); 
    w.icon = document.getElementById('icon'); 
    w.wind = document.getElementById('wind'); 
    w.time = document.getElementById('time'); 
    w.lat = null; 
    w.lon = null; 
    w.cityArray = []; 
    w.weather = null; 

    function sendRequest (url, data) { 

     var request = new XMLHttpRequest(); 
     request.open('GET', url, true); 
     request.send(); 

     request.onreadystatechange = function() { 
      if (request.readyState == 4 && request.status == 200) { 
        data = JSON.parse(request.responseText); 
        console.log(data); 
        return data; 
      } else { 
       console.log(request.status + ': ' + request.statusText); 
      } 
     } 

    } 

    function displayFunc (obj) { 

     console.log('obj ' + obj); 
     w.icon.src = 'http://openweathermap.org/img/w/' + obj.weather[0].icon + '.png'; 

     var timeNow = new Date(); 
     var hours = timeNow.getHours(); 
     var minutes = timeNow.getMinutes() < 10 ? '0' + timeNow.getMinutes() : timeNow.getMinutes(); 
     w.time.innerHTML = hours + ':' + minutes; 

     w.place.innerHTML = 'Place: ' + obj.name; 
     w.description.innerHTML = "Weather: " + obj.weather[0].description; 
     w.temp.innerHTML = "Temperature: " + w.convertToCels(obj.main.temp) + "°C"; 
     w.humidity.innerHTML = "Humidity: " + obj.main.humidity + '%'; 
     w.wind.innerHTML = 'Wind: ' + obj.wind.speed + ' meter/sec'; 
    } 


    w.convertToCels = function(temp) { 
     var tempC = Math.round(temp - 273.15); 
     return tempC; 
    } 


    w.getWeatherFunc = function() { 

     if (navigator.geolocation) { 
      navigator.geolocation.getCurrentPosition(function(location){ 
       w.lat = location.coords.latitude; 
       w.lon = location.coords.longitude; 

       var url = weatherUrl + 'lat=' + w.lat + '&lon=' + w.lon + appid; 

       var result = sendRequest(url, w.weather); 
       console.log(result);  
       displayFunc(result); 
      }); 
     } else { 
      alert('Browser could not find your current location'); 
     } 
    } 


    w.addCityBtn.onclick = function() { 
     var newCity = prompt('Please insert city', 'Kiev'); 

     var gUrl = googleUrl + newCity + googleKey; 
     var newCityWeather = null; 
     sendRequest(url, newCityWeather); 

     var location = newCityWeather.results[0].geometry.location; 
     var newUrl = weatherUrl + 'lat=' + location.lat + '&lon=' + location.lng + appid; 

     sendRequest(newUrl, w.weather); 

      displayFunc(newCity); 
      w.cityArray.push(newCity); 
     } 

    window.onload = w.getWeatherFunc; 

    setInterval(function() { 
     w.getWeatherFunc(); 
    }, 900000); 

} 

您的ajax 返回返回浏览器引擎。由于它的异步您需要创建一个回调:

function sendRequest(url,data,callback){ 

//if the data was received 
callback(data); 
} 

使用这样

sendRequest("yoururl",data,function(data){ 
displayFunc(data); 
}); 
+0

是的,这工作!非常感谢! – Olga

当您第一次将obj传递给函数时,它会将其保存在一个更高的范围内。在那之后,如果你不传递对象,你之前保存的对象将被使用。

var objBkp; 
function displayFunc (obj) { 
    if(undefined === obj) obj = objBkp; 
    else objBkp = obj; 
    // rest of code here 
} 
+0

还是得到了同样的错误 – Olga

+0

我不是试图解决任何错误,我是在回答你问的问题。佩尔帕斯,你应该考虑重申这个问题。 –

+0

我相信这就是我在这里所做的:我有一个全局变量w.weather,我将它传递给函数,并且它应该会改变它的值,但它不是 – Olga

在你sendRequest你逝去的w.weather的唯一的价值,而不是它的参考。 JavaScript不会通过值或引用传递变量,而是通过sharing。所以,如果你想给的价值,您的变量,你应该这样做,你的函数里面sendRequest

request.onreadystatechange = function() { 
    if (request.readyState == 4 && request.status == 200) { 
     w.weather = JSON.parse(request.responseText); 
     console.log(data); 
     return data; 
    } else { 
     console.log(request.status + ': ' + request.statusText); 
    } 
} 

另外,如果您正在使用的属性,你没有通过他们在功能作为参数。除此之外,如果您还创建了get()set()

+0

您一般正确,但链接没有任何待办事项你的答案。空是原始类型,因此按值传递。 –

getWeatherFunc中的console.log(result);会给您带来什么? 我看到的问题是,在displayFunc传递的参数是未定义的。

+0

是的,它给出了undefined – Olga

+0

我知道你还没有评论,但这是一个评论。请删除它 –