What is the type of XMLHttpRequest in JavaScript?

Interestingly, the standard XMLHttpRequest object type is in JavaScript. I found different results depending on the engine.

In Firefox and Chrome:

 typeof XMLHttpRequest //=> "function" 

In Safari:

 typeof XMLHttpRequest //=> "object" 

The W3C specification uses the interface keyword to define XMLHttpRequest , which is not used in practice :

 [Constructor(optional XMLHttpRequestOptions options)] interface XMLHttpRequest : XMLHttpRequestEventTarget { // ... } 

The definition of MDN states that:

XMLHttpRequest is a JavaScript object ...

But Firefox returns "function" , so the term is fuzzy. The definition also states that:

Now it is standardized in W3C.

I looked a little more here and there, but there is no final answer β„’. Whether there is a?

Beyond this point, some additional background


Question Context

I just fixed the error in this code:

 if (typeof XMLHttpRequest === "function") { // do something } 

The error only appeared in Safari 7 so far (no tests in other versions). The code works fine in Firefox and Chrome. Fixed:

 if (typeof XMLHttpRequest !== "undefined") { // do something } 

The problem came from the fact that typeof XMLHttpRequest is the same everywhere ...

+7
javascript safari
source share
2 answers

Safari seems to be wrong here, according to ECMAScript 5 and the Web IDL specification. typeof XMLHttpRequest should return "function" .

The WebIDL specification says :

If an interface is declared with the extended attribute [Constructor] , then the interface object can be called as a function to create an object that implements this interface.

...

The internal [[Call]] method of the interface object behaves as follows:

Meanwhile, the specification for typeof in the ESCAScript 5 specification has a table of return values ​​with entries:

Object (native or host and implements [[Call]] ): "function"

Object (the host does not implement [[Call]] ): The implementation, with the exception of it, cannot be "undefined" , "boolean" , "number" or "string" .

This table shows that any object - native or host - that implements [[Call]] must call typeof to get "function" . The WebIDL specification requires [Constructor] interface objects to implement [[Call]] , so they must give a "function" .

+3
source

If you just want to verify that XMLHttpRequest exists, you can use:

 if (typeof XMLHttpRequest !== "undefined") { // do something } 

or

 if (window.XMLHttpRequest !== undefined) { // do something } 

or

 if (this.XMLHttpRequest !== undefined) { // do something } 
+1
source

All Articles