“this” does not refer to what I want [duplicate]

巧了我就是萌 提交于 2019-12-01 11:33:45

问题


In one of my classes, a method performs AJAX requests. In the callback function of a request, I need to call another method of my object, using this. But this does not refer to my object in this context, so I don't know how to do... Is it only possible ?

To clarify, please consider the following code :

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();

回答1:


You can define a variable to store this in the closure :

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

or use $.proxy :

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

or, if you don't do more than calling myMethod in the callback :

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

In modern browsers you can also use bind. When I don't have to be compatible with IE8 I do

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


来源:https://stackoverflow.com/questions/17020234/this-does-not-refer-to-what-i-want

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!