【问题标题】:Why my XmlHttpRequest's onload props can not use arrow function [duplicate]为什么我的 XmlHttpRequest 的 onload 道具不能使用箭头功能[重复]
【发布时间】:2019-08-01 18:02:23
【问题描述】:

我正在学习 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”的元素具有值,但是当我将函数更改为箭头语法时,该元素根本不会收到任何值。

【问题讨论】:

标签: javascript ajax xmlhttprequest arrow-functions


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      • 2017-12-25
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多