Save a reference to this
before calling $.get
.
MyObject.prototype.myMethod = function () {
var that = this;
$.get('myurl', function (data) {
console.log(that.foo);
});
};
Question
I'm currently diving into Object-oriented programming in JavaScript and I came across a problem. I'm defining an object like below, doing some jQuery stuff inside one of the methods, and I'm wondering what is the best way to access Object properties inside a jQuery method that overrides the 'this' variable.
function MyObject() {
this.foo = 'bar';
}
MyObject.prototype.myMethod = function () {
$.get('myurl', function (data) {
// how to address this.foo here ?
});
};
Solution
Save a reference to this
before calling $.get
.
MyObject.prototype.myMethod = function () {
var that = this;
$.get('myurl', function (data) {
console.log(that.foo);
});
};
OTHER TIPS
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));
};