This question already has an answer here:
- How to access the correct `this` inside a callback? 10 answers
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();