JavaScript对象方法返回语句
在JavaScript中,我创建了一个用户类。我为此编写了一个方法(函数),但无法给出返回语句。这是我的班级:JavaScript对象方法返回语句,javascript,oop,return,Javascript,Oop,Return,在JavaScript中,我创建了一个用户类。我为此编写了一个方法(函数),但无法给出返回语句。这是我的班级: function User() { var isLogedIn = "FukkaMukka"; var mail = ""; var name = ""; //functions this.isLogedInFn = function(callback) { $.post("controller.php?module=logi
function User() {
var isLogedIn = "FukkaMukka";
var mail = "";
var name = "";
//functions
this.isLogedInFn = function(callback) {
$.post("controller.php?module=login&action=test", function(e) {
this.isLogedIn = false; // Here i can't reach the object variable.. why?
return e;
})
}
this.logIn = logIn;
}
回调不会在对象的中执行。解决问题的几种方法:
- 使用
上下文调用
参数
- 你的功能与你的对象有关
- 将对对象的引用存储在变量中,并使用该变量(如Sarfraz建议的)
请参阅代码中的注释。可能重复我很惊讶没有其他人说过这句话,但是。。。在$.post内返回是无用的,因为它是“异步”运行的。另外,
isLoggedIn
是正确的拼写;-)哦,还有,我“结束时不是一个真正的问题”,因为没有给出实际问题的细节,也没有提出关于这个问题的具体问题。如果是,它可以被识别为百万个重复项之一:(我将“this”改为“self”,但不起作用……您还需要定义self
…请参见上面的声明//函数
function User() {
var isLogedIn = "FukkaMukka";
var mail = "";
var name = "";
var self = this;
//functions
this.isLogedInFn = function(callback) {
$.post("controller.php?module=login&action=test", function(e) {
// `this` is no longer in the scope of the function as you would think it would be. in this case `this` iirc will reference the window object.
self.isLogedIn = false;
return e;
})
}
this.logIn = logIn;
}