【问题标题】:JavaScript object method return statement [closed]JavaScript对象方法返回语句[关闭]
【发布时间】:2012-04-19 17:56:22
【问题描述】:

在 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;

}

【问题讨论】:

  • 我很惊讶没有人这么说,但是...... 在 $.post 中返回是无用的,因为它是“异步”运行的。此外,isLoggedIn 是正确的拼写;-)
  • 哦,我也是“关闭为不是一个真正的问题”,因为没有给出实际问题的详细信息,也没有具体问题 有人问过这个问题。如果是,它可以被识别为百万重复之一:(

标签: javascript oop return


【解决方案1】:

回调不会在您的对象的context 中执行。几种解决方法:

  • 使用context 参数调用jQuery.ajax
  • bind()你的函数到你的对象
  • 将对象的引用存储在变量使用中(如 Sarfraz 建议的那样)

【讨论】:

    【解决方案2】:
    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;
    
    }
    

    查看代码中的 cmets。

    【讨论】:

    • 我把“this”改成了“self”,但是没有用……
    • 你还需要定义self...见上面//functions的声明
    猜你喜欢
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 1970-01-01
    相关资源
    最近更新 更多