嗨,我有函數,它返回一個JavaScript類,但在運行時返回值是未定義的。當我將返回值設置爲某個全局變量時,它在Chrome開發者控制檯上給了我正確的結果。爲什麼會發生?Javascript函數類對象返回undefined
var globalData;
$(document).ready(function(){
var request = postRequest("contact", dt, elem);
globalData = request;
console.log(request.status); //this gaves me undefined
});
function returnObj(status, message, projects) {
this.status = status;
this.message = message;
this.projects = projects;
}
function postRequest(method, vars, elem) {
var result = new returnObj();
$.post('api.aspx',
{
method: "test"
},
function (data, status) {
var resultObject = $.parseJSON(data);
result.status = resultObject.status;
result.message = resultObject.message;
result.projects = resultObject.projects;
});
return result;
}
http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-電話 – naortor
帖子是異步的,當函數返回「result」後肯定還沒有完成! – Baro