Skip to content

XMLHttpRequest.onload constructor in Javascript?

When making a new XMLHttpRequest, like so

let http = new XMLHttpRequest();

There is a method (property ?) called onload. My question is, why we can assign a function to it? like this

http.onload = function(){};

If onload is a property in XMLHttpRequest, the value of it will change when we assign a new value to it, like a function, right?

What is the XMLHttpRequest.onload constructor looks like? I am really confused about this.

Answer

When we first started writing HTML event handlers, we would write

<button onclick="alert('Hey you')"> Say Hi</button>

When you translate the HTML into the DOM, you get a reference to an object and you can also set that event handler by setting a property to a function. The browser will call that function for you when the user clicks the button. This is a poor man’s event system using properties as callbacks.

Those were the two ways to set an event handler:

  • XML attribute
  • DOM element reference by setting a property

After a while, they realized that multiple listeners may need to be set (overwriting a property would override the previous listener). We created hacks to allow setting multiple handlers by creating function that called other functions and there was a need for a real event system. The DOM element became an EventTarget, and you can now use a more common Event interface.

buttonEl.addEventListener('click', () => console.log('clicked'));
buttonEl.addEventListener('click', () => console.log('second handler'));

So we have three different ways of setting events. XmlHttpRequest also implements its own XMLHttpRequestEventTarget event target, so you can set “events” in both ways, through callback properties and addEventListener.


In your question, you said: “What is the XMLHttpRequest.onload constructor looks like?” You probably meant how can we override the onload property because a property doesn’t have a constructor, its value has a constructor, but we typically assign it using a literal. It’s initially unset (undefined), if it’s never set, it won’t get called.