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)
您可以定义要存储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)