0

Coming from a class-based OOP background (C++/Java/C#), I'm on the path of learning object-oriented JavaScript. I often read advice about using Object.create(...) instead of new ... when dealing with objects is JS.

So I tried to create AJAX calls that way :

var req = Object.create(XMLHttpRequest);
req.open(...); // TypeError: req.open is not a function

Shouldn't open be in req's prototype chain ?

I also tried to apply the XMLHttpRequest constructor function to my object :

var req = Object.create(XMLHttpRequest);
XMLHttpRequest.apply(req, null); // Constructor XMLHttpRequest requires 'new'

Just when I thought I was out of trouble with JS's OO way, this pulls me back in :)

Many thanks to those who'll help me understand what's going on here.

Baptiste
  • 115
  • 1
  • 11

1 Answers1

1

XMLHttpRequest is designed to return the request object when invoked as a constructor: var req = new XMLHttpRequest(). Object.create(proto) creates a new object with the prototype as the first parameter.
The 2 approaches do different things: object creation and initialisation (first case) and simply create a new object with prototype (second case).


Of course you could try to accomplish the same thing this way (not recommended):

var obj = Object.create(XMLHttpRequest.prototype);
XMLHttpRequest.call(obj); // initialize the request

which is almost equivalent to:

var obj = new XMLHttpRequest();

But you receive an error:

Uncaught TypeError: Failed to construct 'XMLHttpRequest': Please use the 'new' operator


So the correct solution is to use new XMLHttpRequest().
Take a look at the Fetch API, which is near what you try to accomplish. But it has a limited support in browsers.

Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41