【发布时间】: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”的元素具有值,但是当我将函数更改为箭头语法时,该元素根本不会收到任何值。
【问题讨论】:
-
=>函数未设置this -
箭头函数的基础....什么是
thisdeveloper.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
用
request替换this在箭头版本中可以解决问题
标签: javascript ajax xmlhttprequest arrow-functions