0

When I am using an arrow function in xhr.onload, I don't get a response. However, if I use a normal function like xhr.onload = function(){} then I get the response. Why does the code before not work like it does when using xhr.onload = function(){}?

let btn = document.getElementById("button");

btn.addEventListener("click" , function(){
let xhr = new XMLHttpRequest();
xhr.open("GET" , "sample.txt" , true);
xhr.onload = () => {
    if(this.status === 200){
         console.log(this.responseText);
    }
}
xhr.send();
})
Jack Moody
  • 1,590
  • 3
  • 21
  • 38
Rakib Uddin
  • 880
  • 1
  • 6
  • 17
  • 4
    Don't use `this` inside `onload` callback. It doesn't refer to `xhr` as you think. So use `xhr` instead `this`. – hindmost Jan 16 '19 at 16:58
  • @hindmost you beat me to it, +1 – Harry Chilinguerian Jan 16 '19 at 16:59
  • @hindmost You shouldnt post what is essentially a complete answer as a comment. That is an abuse of the comment system. If somebody posts an incorrect answer as a comment there is no way to vote the answer down and the OP may think it is true. – Marie Jan 16 '19 at 17:00
  • It's not an incorrect answer if its posted as a comment. – Andy Jan 16 '19 at 17:03
  • @RakibUddin you should read on on [fat arrow functions](https://stackoverflow.com/a/28372106/2647442) and [javascript closures](https://stackoverflow.com/a/12931785/2647442). If you plan on sticking with javscript you will NEED to know about these – Marie Jan 16 '19 at 17:04
  • @Andy Comments are for asking for clarification and providing advice. not answering questions. What you posted is an answer to the question the OP was asking. That is an abuse of the comment system because users cant vote on the answer you supplied. "Answer" being "a thing said, written, or done to deal with or as a reaction to a question,", not the thing created when you click the answer button. – Marie Jan 16 '19 at 17:05
  • If comments are for "asking for clarification and providing advice" isn't what you're doing an abuse of the comment system? Perhaps this should be taken to meta. – Andy Jan 16 '19 at 17:10

1 Answers1

3

The context of this of the onload function should be the original XMLHttpRequest, but using the arrow function you don't have a context assigned so the this will more than likely be parent scope or window. That's going to be the issue.