Search code examples
javascriptxmlhttprequest

What type of function is this?


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();

This code represent an XHR request and response. I was watching a tutorial on AJAX and xhr.onreadystatechange was described as an object property. I know that function expressions are anonymous functions assigned to variables but what about anonymous functions assigned to object properties. What is the name of this kind of function that is called when an object property updates? This hasn’t really been taught in basic javascript or ES6 from what I can see.


Solution

  • The function that you are assigning to xhr.onreadystatechange is called an event handler. This event handler function gets executed when the actual event 'readystatechange' gets fired in your case.