0

I was learning to make HTTP requests in JS using XMLHTTpRequests. I know this method is not used much. but I have a doubt regarding this.

When I am using arrow functions in addEventListener then its console logging me undefined.

As arrow functions don't have its own This context so it takes it from its parent.So why exactly here it's not working?

Is my concept about it is wrong?

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", () => {
  console.log(this.responsetext); // undefined
});
oReq.addEventListener("error", () => {
  console.log("error");
});
oReq.open("GET", "https://swapi.dev/api/planets/");
oReq.send();
console.log("Request Send");
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Try this: `window.name="I am the window"; var oReq = new XMLHttpRequest(); oReq.addEventListener("load", () => { console.log(this.name) }); ` and you will understand – mplungjan Jun 03 '20 at 17:06
  • Now change to `console.log(oReq.response);` and it works – mplungjan Jun 03 '20 at 17:09

0 Answers0