"这个"并不是指我想要的东西

lit*_*ude 1 javascript ajax callback this

在我的一个类中,一个方法执行AJAX请求.在请求的回调函数中,我需要使用调用我的对象的另一个方法this.但是this在这种情况下并没有提到我的对象,所以我不知道该怎么做......它是否只有可能?

为澄清,请考虑以下代码:

function MyClass(arg) { 
    this.foo = arg; 
} 

MyClass.prototype = { 
    myMethod: function() { 
        console.log("I am myMethod");
    },
    myGet: function (){
        $.get("http://example.iana.org/",function(data){
            this.myMethod(); // does not work, because 'this' does not refer to my object
        });
    }
} 

var obj = new MyClass("Javascript is complicated"); 

obj.myGet();
Run Code Online (Sandbox Code Playgroud)

Den*_*ret 7

您可以定义要存储this在闭包中的变量:

myGet: function (){
    var _this = this;
    $.get("http://example.iana.org/",function(data){
        _this.myMethod();
    });
}
Run Code Online (Sandbox Code Playgroud)

或使用$ .proxy:

myGet: function (){
    $.get("http://example.iana.org/", $.proxy(function(data){
        this.myMethod();
    }, this));
}
Run Code Online (Sandbox Code Playgroud)

或者,如果你没有做多次调用myMethod回调:

myGet: function (){
    $.get("http://example.iana.org/", $.proxy(this.myMethod, this));
}
Run Code Online (Sandbox Code Playgroud)

在现代浏览器中,您也可以使用bind.当我不必与IE8兼容时,我做到了

myGet: function (){
    $.get("http://example.iana.org/", this.myMethod.bind(this));
}
Run Code Online (Sandbox Code Playgroud)

  • @emmasculateur就个人而言,我对附加变量没有任何问题,特别是当你给它一个不太通用的名字时,但是`$ .proxy`可能会使意图更清晰. (2认同)
  • @MattHarrison对此不太确定 - 只要你创建一个闭包来存储当前的`this`引用就可以正常工作,因为这基本上是`$ .proxy`在内部做的. (2认同)