I’m attempting to have a javascript object run a deferred method and when it’s .done() call a function in that same object. I’m having issues because “this” becomes the deferred object instead of the object that called it.
PageObject.prototype.successFunction = function() {
console.log(arguments);
return console.log(this.name + " Success function called");
};
PageObject.prototype.loadPage = function(url) {
return $.when($.mobile.loadPage("pages/" + url))
.done(this.successFunction);
};
var pg = new PageObject();
pg.loadPage("test.html");
How do I send “this” into the successFunction? This PageObject is going to be extended by others as well, so knowing “this” when running successFunction will be very handy.
It seems simple, and probably has a simple answer. I was looking into .apply() but I’m not sure it helped. This post on stack overflow was helpful a little bit, but it broke the minute I put it into the .done() function.
jQuery’s
proxywill return a function bound to a specific context:There is also ES5’s
bindwhich operates similarly but needs to be shimmed in older browsersapplyandcallcan execute a function immediately with the specified context, butproxyandbindreturn a function that can be used later or passed to other functions.