I have two Javascript “objects” similar to so….
var Object2 = new (function() {
this.FetchData = function(callback) {
// do some stuff
callback(data);
};
});
var Object1 = new (function() {
this.DisplayStuff = function() {
};
this.LoadData = function() {
Object2.FetchData(this.OnData);
};
this.OnData = function(data) {
// this == window
this.DisplayStuff(); // doesn't work
};
});
When Object1 receives the callback to OnData, the value of “this” is set to window. Is there any way I can get around this so that the value of “this” inside of OnData will be the instance of Object1 instead of window?
The simple way of doing it is storing a reference to this in a variable, then using the call() method:
If you’re doing this a lot, you might want to consider using the .bind() method on the function prototype in ECMAScript 5th edition. This method can be implemented where unsupported:
And the resulting function call:
PrototypeJS – bind()