【发布时间】:2014-10-29 07:53:58
【问题描述】:
我正在尝试从here 获取天气预报。这工作正常,我得到了我的价值。如果我进行正常的 ajax 调用,它工作正常。
但是:
function Weather() {
var self = this,
weatherUrl = 'http://api.openweathermap.org/data/2.5/weather?id=',
value = null;
function getWeatherForCity(id) {
$.ajax({
url: weatherUrl + id,
async: false,
success: function (data) {
console.log(data);
value = data;
}
});
}
self.getWeatherForCity = function (id) {
var cast = value;
console.log(cast);
return cast;
};
}
来电:
weather = new Weather();
console.log(weather.getWeatherForCity('2878234'));
如果我通过这些函数进行调试,我会在成功回调函数中得到良好的结果,但是强制转换变量为空,就像它从未被触及过一样?
谁能给我解释一下?
【问题讨论】:
-
让我们从
async: false是非常糟糕且已被弃用的事实开始。 -
嗯,我知道,但这不是真正的答案。
-
问题是你从来没有真正打电话给
getWeatherForCity()。因此结果。 -
getWeatherForCity是一个私有函数,当你做weather.getWeatherForCity('2878234')时它不会被调用 -
这怎么可能是私有函数?它在物体上
标签: javascript jquery ajax