构造函数需要一些时间,并且在调用该方法时,尚未定义this.folders
。如何允许getIt()
等待构造函数完成?
function test() {
var t=this;
$.getJSON('~.php?task=getFolders&dummy='+new Date().getTime(), function(returned){
t.folders=returned;
});
}
test.prototype.getIt = function() {
return this.folders;
};
var myObj = new test();
console.log(myObj.getIt());
最佳答案
由于$.getJSON()
是异步的,因此无法阻止在填充test()
之后返回。
您可以使用回调:
function test(callback) {
$.getJSON('~.php?task=getFolders&dummy='+new Date().getTime(), function(returned){
callback(returned);
});
}
var myObj = new test(function (folders) {
console.log(folders);
});
或一个承诺(在此示例中,使用Q库):
function test() {
var t = this;
t.folders = Q.defer();
$.getJSON('~.php?task=getFolders&dummy='+new Date().getTime(), function(returned){
t.folders.resolve(returned);
});
}
test.prototype.getIt = function() {
return this.folders.promise;
};
var myObj = new test();
myObj.getIt().done(function (folders) {
console.log(folders);
});