1

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?

Dreamer
  • 1,139
  • 9
  • 18

1 Answers1

4

This is simpler :

this.onload = this.onDataLoaded.bind(this);

Another handy solution will come with ES6, arrow functions with their lexical this binding :

this.onload = () => { this.onDataLoaded() }

(you can already use them in Firefox)

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758