【发布时间】:2022-01-27 09:05:20
【问题描述】:
const xhr = new XMLHttpRequest(),
method = "GET",
url = "https://developer.mozilla.org/";
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
// In local files, status is 0 upon success in Mozilla Firefox
if(xhr.readyState === XMLHttpRequest.DONE) {
var status = xhr.status;
if (status === 0 || (status >= 200 && status < 400)) {
// The request has been completed successfully
console.log(xhr.responseText);
} else {
// Oh no! There has been an error with the request!
}
}
};
xhr.send();
此代码表示 XHR 请求和响应。我正在观看有关 AJAX 的教程,并且 xhr.onreadystatechange 被描述为对象属性。我知道函数表达式是分配给变量的匿名函数,但是分配给对象属性的匿名函数呢?对象属性更新时调用的这种函数的名称是什么?据我所知,这并没有真正用基本的 javascript 或 ES6 教授过。
【问题讨论】:
-
这是一个事件回调函数。
-
就像你给一个元素分配
.onclick一样,当有人点击它时执行一个函数。