【问题标题】:"this" does not refer to what I want [duplicate]“这个”不是指我想要的[重复]
【发布时间】:2013-06-10 09:00:08
【问题描述】:

在我的一个类中,一个方法执行 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();

【问题讨论】:

    标签: javascript ajax callback this


    【解决方案1】:

    你可以定义一个变量来存储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));
    }
    

    【讨论】:

    • +1 $.proxy 更酷
    • @emmasculateur 就我个人而言,我对附加变量没有任何问题,尤其是当你给它一个不太通用的名称时,但$.proxy 可能会使意图更清晰。
    • 有时无法使用附加变量。例如,如果您在编写异步代码时对回调有很多深入的了解,您可能会失去对原始this 的引用。在这种情况下,$.proxy 可以出手相救。
    • @MattHarrison 对此不太确定 - 只要您创建一个闭包来存储当前的 this 引用,它应该可以正常工作,因为这基本上是 $.proxy 在内部所做的。跨度>
    • @MattHarrison “更好”是相对的 - bind$.proxy 是较短且语法上最甜美的语法。我的意思是,在使用这些的地方,您还可以在其周围包装另一个函数,存储 this 引用,然后您可以将其用于 call/apply 内部函数。
    猜你喜欢
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 2018-08-09
    • 2014-10-09
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多