0

I am learning Ajax and ES6, so i want to bind a function to an onload property from the XmlHttpRequest obj. At first, i write an anoynymous function and it runs OK. But when i changed the function to arrow syntax, the element with id "text" did not have any value.

//this code runs normally
xhr.onload = function() {
   if (this.status === 200) {
      document.getElementById("text").innerText = this.responseText;
   } else if (this.status === 404) {
      document.getElementById("text").innerText = "Not Found!";
   }
};


// this code can not run
xhr.onload = () => {
   if (this.status === 200) {
      document.getElementById("text").innerText = this.responseText;
   } else if (this.status === 404) {
      document.getElementById("text").innerText = "Not Found!";
   }
};

I expect my element with id "text" to have value, but when i changed my function into arrow syntax, the element dont receive any value at all.

Sonny
  • 166
  • 1
  • 4
  • 12

2 Answers2

0

Arrow functions retain the this-ness of the outer function. In the top example, this refers to xhr. In the bottom function, this refers to something else (that's impossible to determine from the given code).

Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
0

The problem here is that this has no context within the onload function. So, when you check the condition this.status it is looking for a this that is scoped to the containing function. However, arrow functions by nature scope to the parent.

silencedogood
  • 3,209
  • 1
  • 11
  • 36