I often have code like this:
function Object() {
}
Object.prototype.getData() {
// THIS LINE:
var object = this;
$.ajax({
url: '...'
, success: function(data) {
object.onLoadData(data);
}
})
}
var o = new Object();
o.getData();
My question: what’s the preferred paradigm for the “var object = this” bit above? I’ve seen this:
var self = this;
Which looks good, and I’ll probably steal this method. What is the most common way of referring to parent object from within anonymous functions? Are there cleverer ways of doing this? I often find myself putting the “var object = this;” at the top of most object methods, and it seems like there might be some tricky way to avoid this.
Thanks!
Given your code, don’t use a variable.
Use the
context:parameter to set thethisvalue in the callbacks.If the question wasn’t meant to only deal with
$.ajax, then I’d usebind()[docs] to bind thethisvalue to the function.If you need to support browsers that don’t have
.bind(), then there’s a shim in the docs link I provided that you can include.