I often write Javascript code of the form:
MyClass.prototype.loadData = function() {
var oReq = new XMLHttpRequest();
var obj = this;
oReq.onload = function() { obj.onDataLoaded(); }
oReq.open("get", url, true);
oReq.send();
}
The part that seems unelegant is the var obj=this
to assign the current object to a temporary variable, (obj
) just to be able to refer to it in the oReq.onload
function. For all other variables besides this
, that would not be necessary, as they are automatically part of the closure, and thus can be referred to in onload()
. But this
is not part of the closure and instead always (?) refers to the object that the method is bound to.
So is there a more idiomatic way of accessing the current this
object from within a function being bound to another object than to assign this
to a temporary variable first and then use that variable?