Search code examples
javascriptajaxxmlhttprequestarrow-functions

Why my XmlHttpRequest's onload props can not use arrow function


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.


Solution

  • 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.