JavaScript对象方法返回语句

时间:2012-04-19 17:56:22

标签: javascript oop return

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

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;

}

2 个答案:

答案 0 :(得分:1)

回调未在对象的context中执行。有几种解决方法:

  • 使用context参数
  • 致电jQuery.ajax
  • bind()您的功能对象
  • 在变量用途中存储对象的引用(如Sarfraz建议的那样)

答案 1 :(得分: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;

}

在代码中查看评论。