Just create a variable in the scope of the outer function to preserve its context:
MyObject.prototype.myMethod = function () {
var self;
self = this;
$.get('myurl', function (data) {
// how to address this.foo here ?
self.doStuff();
});
};
For callbacks, you may want to make use of jQuery.proxy
, which is jQuery's souped-up version of Function.prototype.bind
:
function MyObject(selector) {
this.foo = 'bar';
$(selector).on('click', $.proxy(this, 'myMethod'));
}
MyObject.prototype.myMethod = function (e) {
console.log(this.foo); //'bar'
};
For your case specifically, you can make use of jQuery.proxy
to generate a callback for the $.get
success function:
MyObject.prototype.myMethod = function () {
$.get('myurl', $.proxy(this, 'myCallback'));
};
MyObject.prototype.myCallback = function (data) {
console.log(this.foo); //'bar'
};
Alternatively, you can write the proxy inline:
MyObject.prototype.myMethod = function () {
$.get('myurl', $.proxy(function (data) {
console.log(this.foo); //'bar'
}, this));
};