Simple closure for cross browser XHR instance

Yes that is right, there are many libraries to handle XHR, but raw JS is always fun!

There are many ways of doing this, but here is a unique way of getting an XHR instance.

A simple closure, that tries to create a simple XHR instance :

var req = (function () {
    try {
        return new(this.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0')
    } catch (e) {}

The 'req' var dump on V8 would be like :

readyState ":0,"
onloadstart ":null,"
withCredentials ":false,"
onerror ":null,"
onabort ":null,"
status ":0,"
responseXML ":null,"
onload ":null,"
onprogress ":null,"
upload ":{"
onloadstart ":null,"
onabort ":null,"
onerror ":null,"
onload ":null,"
onprogress ":null},"
statusText ":"","
responseText ":"","
UNSENT ":0,"
OPENED ":1,"
DONE ":4

So, thus a silly script was made just for the LOLz of it! Do suggest your way ;)

Share this