<分区>
我在下面有这段代码。
var user = new user();
function user() {
// returns true if the account is password protected
function isPasswordProtected(data, callback) {
//check if the account is a password protected account, and if so request the password.
$.post('user_functions/ifpasswordprot.php', {uid: data['uid']}, function(data) { return callback(data);});
}
// function that returns 1 if the user is password protected
this.getPPStatus = function() { return isPasswordProtected({uid: this.userid}, function(data) { return data; }); };
}
这旨在创建一个存储用户对象,可以从站点内的其他地方引用。不仅如此,但这是此处相关的代码。
我试图从另一个页面查明登录的用户是否使用密码保护了他们的帐户,如下所示:
alert(user.getPPStatus());
然而,这总是以 undefined
的形式出现。
我不是 JavaScript 中对象方面的专家,也不是匿名函数用户方面的专家。任何人都可以解释为什么这行不通吗?似乎每次都有足够的返回,应该没问题。
解决方案
这是一个异步问题,所以:
var user = new user();
function user() {
// returns true if the account is password protected
function isPasswordProtected(data, callback) {
//check if the account is a password protected account, and if so request the password.
$.post('function/get-ifpasswordprotected.php', {uid: data['uid']}, function(data) { callback(data);});
}
// function that returns 1 if the user is password protected
this.getPPStatus = function(**callback**) { isPasswordProtected({uid: this.userid}, **callback**); };
}
然后
user.getPPStatus(function(result) {
**DO STUFF HERE**
});
完全不知道这是否是好的 javascript 但是嘿,它有效...:)