Javascript 函数、对象和匿名函数
我有下面的代码Javascript 函数、对象和匿名函数,javascript,function,Javascript,Function,我有下面的代码 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 passw
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());
但是,这总是显示为未定义
我不擅长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,但嘿,它可以工作…:) 这不起作用的原因有三个:
默认情况下,$.post
是异步的,因此如果isPasswordProtected
使用它来获取信息,它无法返回标志,因为返回时还没有结果。有关详细信息,请参阅
即使$.post
是同步的(它可以带有一个选项,但这不是一个好主意),$.post
也不会使用其回调的返回值,因此该回调中的返回值也不会做任何事情
即使isPasswordProtected
要返回回调的结果,如果回调是同步的(它不同步),isPasswordProtected
从不设置返回值(在该代码中,没有从isPasswordProtected
返回,只有从回调到$.post
)
上面的链接解释了如何更改getPPStatus
和isPasswordProtected
以解决异步问题,这也从本质上解决了使用return
s的问题。问题的标题听起来像书/电影的标题@沃曼-是的,我看到了,詹姆斯·斯派德在itGargh很出色,又是异步的!我将编辑我的解决方案到我的第一篇文章不久。。。谢谢@亚历山大·邦廷:没必要这么做。很高兴上面的帮助!