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.

3
  • XMLHttpRequest is a function. Commented May 3, 2016 at 14:41
  • "I often read advice about using Object.create(...) instead of new ..." - no. Please read it again. They are not exchangeable. Commented May 3, 2016 at 15:24
  • ya, try print out these two will help you understand . console.log(new XMLHttpRequest()); console.log(Object.create(XMLHttpRequest)); Commented May 3, 2016 at 15:41

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.