由网友(用微笑掩盖了落寞)分享简介:在我的一个类,一个方法执行AJAX请求。在请求的回调函数,我需要调用我的对象的另一种方法,使用这。但这不引用我在这方面的对象,所以我不知道该怎么办?难道仅仅是可能的吗?要澄清,请考虑以下code:函数MyClass的(ARG){this.foo = ARG;}MyClass.prototype = {在myMetho...
在我的一个类,一个方法执行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,本));
}
在现代浏览器中,你还可以使用绑定。当我没有与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));
}
相关推荐
最新文章