I have the following code for the definition of a class
var class1 = function () {
this.classData = 'value1';
this.func1 = function(callback) {
$.ajax({
'url': '/somewhere',
'dataType': 'json',
'type': 'POST',
'data': {
options: 'some text'
},
'success': function (data, textStatus, jqXHR) {
callback(data); // <<<<<< THIS LINE
}
});
};
};
and then I call the class like this
var obj1 = new class1();
obj1.func1(function (d) {
this.classData = d;
});
But this doesn’t seem to work because, inside the sucess function, when the callback function is called at the line marked in the code above, it has it’s this object pointing to the window and not the obj1 value.
What am I doing wrong here, how do I fix it?
This isn’t really a scope problem but a context one.
this, when your function is called, is the receiver of the function at the time of calling, not the objectobj1.Do this :
This is the right way.
If your callbacks are all meant to have the instance of class1 as receiver, you may also do this :