"本"并不是指我想要什么 [英] "this" does not refer to what I want

查看:177
本文介绍了"本"并不是指我想要什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个类,一个方法执行AJAX请求。在请求的回调函数,我需要调用我的对象的另一种方法,使用。但不引用我在这方面的对象,所以我不知道该怎么办?难道仅仅是可能的吗?

要澄清,请考虑以下code:

 函数MyClass的(ARG){
    this.foo = ARG;
}

MyClass.prototype = {
    在myMethod:函数(){
        的console.log(我是在myMethod);
    },
    myGet:函数(){
        $获得(http://example.iana.org/功能(数据){
            this.myMethod(); //不起作用,因为这指的不是我的对象
        });
    }
}

VAR OBJ =新MyClass的(Javascript是复杂的);

obj.myGet();
 

解决方案

您可以定义一个变量来存储在封闭:

  myGet:函数(){
    VAR _this =这一点;
    $获得(http://example.iana.org/功能(数据){
        _this.myMethod();
    });
}
 

或使用 $ .proxy

  myGet:函数(){
    $获得(http://example.iana.org/,$ .proxy(功能(数据){
        this.myMethod();
    }, 本));
}
 

或者,如果你不这样做,比回调调用 myMethod的

  myGet:函数(){
    $获得(http://example.iana.org/,$ .proxy(this.myMethod,本));
}
 

在现代浏览器中,你还可以使用<一个href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind"相对=nofollow>绑定。当我没有与IE8兼容怎么办

  myGet:函数(){
    $获得(http://example.iana.org/,this.myMethod.bind(本));
}
 

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

解决方案

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

这篇关于&QUOT;本&QUOT;并不是指我想要什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆