【问题标题】:What type of function is this?这是什么类型的函数?
【发布时间】: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一样,当有人点击它时执行一个函数。

标签: javascript xmlhttprequest


【解决方案1】:

您分配给 xhr.onreadystatechange 的函数称为事件处理程序。在您的案例中触发实际事件“readystatechange”时,将执行此事件处理函数。

【讨论】:

    【解决方案2】:

    这是一个 event handler,与 callback 略有不同。

    【讨论】:

      猜你喜欢
      • 2020-01-29
      • 1970-01-01
      • 2010-10-27
      • 1970-01-01
      • 2012-05-16
      • 2020-06-26
      • 2012-02-13
      • 1970-01-01
      相关资源
      最近更新 更多