0

What is difference between using this keyword vs variable name in XMLHttpRequest callback?

var req = new XMLHttpRequest();
req.open("GET", encodeURI(uri), true);
req.onreadystatechange = function () {
    if (this.readyState == 4) {
        req.onreadystatechange = null; //avoid memory leaks
        if (this.status == 200) {
            var res = JSON.parse(req.responseText).d;
            console.log(res);
        }
    }
};
req.send();

Can I just use req instead of this, like if (req.readyState == 4)?

synergetic
  • 7,756
  • 8
  • 65
  • 106
  • Yes, you can use both. In this case, there is no [difference](http://stackoverflow.com/questions/10711064/javascript-object-literal-reference-in-own-keys-function-instead-of-this) (unless someone overwrites `req`) – Bergi Jun 17 '15 at 05:33
  • 1
    @KunalPradhan: No, his `this` is not referring to a function. – Bergi Jun 17 '15 at 05:34
  • Did you *try* it? What was the result? – Felix Kling Jun 17 '15 at 05:36

2 Answers2

0

There is no difference in onreadystatechange handler by default this refers to the XMLHttpRequest object itself.

So yes, you can use either this or req

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

I myself have encountered this similar problem recently, but I extended it to more general case: which context does this resolved to in callback?

regard to 3 prevalent callback type: setTimeout, XMLHttpRequest, DOM

  • I read from the doc for first type, setTimeout, this will resolved to window object

  • for XMLHttpRequest situation, this will resolved to XMLHttpRequest object itself, https://stackoverflow.com/a/6542261/4730119 this link will give you a explain and here is my test, for which I GET requested api.json's content is a plain simple object and successfully printed in console, notice I used this.responseText, not like most book taught using XHR object request.responseText enter image description here

  • and last for DOM, it's just like XHR, this will resolved to object for which the callback added

    document.querySelector('input')
    .addEventListener('input', function(e){console.log(this)});
    // will print input object
    
Community
  • 1
  • 1
dispute
  • 1,424
  • 13
  • 17