Javascript Variable Not Declaring in Function's Scope
I've been working on some simple AJAX functions recently, using MooTools. My problem lies in the code immediately following:
function changePage(id, url) {
var c = false,
r = null;
for (i = 0; i < history.length; i++) {
if(history[i]['id'] === id) {
console.log('cached');
r = history[i].response;
c = true;
}
}
if(!c) {
makeRequest(url, function(response) {
r = response;
history.push({id: id, response: response});
});
}
changeBackground('_background', {color: r.bgColor, image: r.bgImage});
lightboxContents(开发者_JAVA技巧generateArticle(r.article.id, r.article.title, r.article.body, r.article.timestamp));
return true;
}
Here, whenever the code is executed (it's routed via a click), I'm sent the error "'r' is not defined" - a statement that, in my opinion, is woefully incorrect.
I have, for that matter, also tried replacing 'r' with a global variable using the 'window' object - same problem.
I'm ever puzzled by this simple problem, and would be worlds grateful if someone with fresh eyes could point out my error.
Thanks for your time! Timon
r
is most likely undefined because it looks like makeRequest
is an asynchronous AJAX call, meaning that its callback function is only invoked once the request completes. Since the call is asynchronous, the JS runtime does not wait there, and continues executing the statements after it, which in your case are the calls to changeBackground
, and generateArticle
. However, as the AJAX call has not returned by this time and the callback hasn't been invoked, r
is still null. So trying to access any property on r
like r.bgColor
will throw a ReferenceError
.
It seems like you are trying to use r
before you give it a value, while it is still null
. When you load your page, there is no history so r
wont get a value. And then you have an async function assigning a value to r
but the code that needs r
to have a value will run before the async code has executed.
精彩评论