0

I was studying async, callback and waiting for file. I came across the given example and I am having a hard time understanding whom does "this" given in this code belongs to. Please help.

function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

function getFile(myCallback) {
  let req = new XMLHttpRequest();
  req.open('GET', "mycar.html");
  req.onload = function() {
    if (req.status == 200) {
      myCallback(this.responseText); // Refering to this- "this"
    } else {
      myCallback("Error: " + req.status);
    }
  }
  req.send();
}

getFile(myDisplayer);
<div id="demo"></div>
connexo
  • 53,704
  • 14
  • 91
  • 128
Ryan
  • 37
  • 3
  • You can store `this.responseText` in a variable inside if, before myCallback(). print the variable. Maybe that will help you understand what's going on – nluizsoliveira Nov 21 '21 at 07:23
  • 1
    EventHandlers are always invoked with `this` set to the `currentTarget` of the event; in this case, it’s `req`. But you should always use `addEventListener` instead. You should also consider using the Fetch API instead of XHR. – Sebastian Simon Nov 21 '21 at 07:27

0 Answers0