我遇到了javascript函数回调问题。
例如我有这样的代码:
var BASE = {
// Constructor of the class
createNew: function(name) {
var base = {};
base.ajax = function(callback, url) {
// Create XMLHTTPRequest object
var httpRequest;
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function() {
// Check status of our request
// this is called on every state change
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
// call the callback function
callback.call(httpRequest.responseText);
}
};
httpRequest.open("GET", some_url, true);
httpRequest.send();
};
return base;
}
};
然后创建一个继承BASE的类:
var Test = {
createNew: function() {
var test = BASE.createNew();
test.json = {};
test.ajax( function(){
test.json = JSON.parse( this );
});
return test;
}
};
然后我创建另一个继承Test的类myTest:
// create class for 300x250
var myTest = {
createNew: function() {
var mytest = Test.createNew();
return mytest;
}
};
var mytest = myTest.createNew();
console.log(mytest.json);
然而,当我尝试console.log(mytest.json)时,我无法获取数据。我知道这是因为在Test类中,json是在ajax函数中,但我不知道如何解决这个异步问题,任何想法?