-2

在 JavaScript 中,我创建了一个 User 类。我为此写了一个方法(函数),但我不能给出一个返回语句。这是我的课:

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;

}
4

2 回答 2

1

回调不在对象的上下文中执行。几种解决方法:

  • 使用参数调用jQuery.ajaxcontext
  • bind()你的函数到你的对象
  • 将对象的引用存储在变量使用中(如 Sarfraz 建议的)
于 2012-04-19T17:59:39.230 回答
0
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;

}

查看代码中的注释。

于 2012-04-19T17:59:40.427 回答