javascript - "this"不是我想要的

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

最佳答案

你可以在闭包中定义一个变量来存储this:

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

或使用 $.proxy :

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

或者,如果您只在回调中调用 myMethod:

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

在现代浏览器中,您还可以使用 bind .当我不必与 IE8 兼容时,我会这样做

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

关于javascript - "this"不是我想要的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17020234/

相关文章:

javascript - 基本回调函数结果

javascript - 简化/模块化您的 JavaScript 代码

javascript - 相对于点javascript放置对象

asp.net-mvc - 如何在ASP MVC中返回JSON结构

php - 如何在php中使用delete方法获取ajax发送的值

javascript - 如何在不使用参数的情况下创建 javascript 函数的实例

javascript - 在类和构造函数中访问 ES6/ES7 静态类变量

javascript - 如何使用 HTMLElement.classList(.toggle)?

php - 如何在html中将javascript变量传递给php? (维基百科解析)

javascript - Rails - Turbolinks - 回调