为什么我的 XmlHttpRequest 的 onload 道具不能使用箭头功能

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

我正在学习 Ajax 和 ES6,所以我想将一个函数绑定到一个 onload 属性 来自 XmlHttpRequest 对象。起初,我写了一个匿名函数,它运行正常。但是当我将函数更改为箭头语法时,id 为 "text" 的元素没有任何值。

//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!";
   }
};

我希望我的 ID 为 "text" 的元素有价值,但是当我将我的函数更改为箭头语法时,该元素根本没有收到任何值。

箭头函数保留了外部函数的 this-ness。在上面的示例中,this 指的是 xhr。在底部函数中,this 指的是其他东西(无法从给定的代码中确定)。

这里的问题是 thisonload 函数中没有上下文。因此,当您检查条件 this.status 时,它正在寻找作用域为包含函数的 this。然而,箭头函数本质上作用于父级。