Anil Namde
Anil Namde

Reputation: 6618

How to extend XMLHttpRequest object in JavaScript?

I would like to extend the existing XMLHttpRequest object so that it should work with all the browsers. Now I have been trough with JS inheritance and things however before starting I would like to see good example of it.

HTML5 has upload and progress events stuff which I would like to implement in inherited new object which can behave even if the feature is not supported by not introducing JS errors to client side. So I would like to achieve something like this:

Class XMLHttpRequest{}
Class UploadXMLHttpRequest: XMLHttpRequest{}

Where additional methods can be attached to UploadXMLHttpRequest class like following.

UploadXMLHttpRequest.prototype.uploadFile = function(file){

}

Considering YUI, jQuery and others are good in market no one really wants to do this made it little difficult for me to find good resources.

Upvotes: 4

Views: 3475

Answers (1)

Marcel Korpel
Marcel Korpel

Reputation: 21763

Don't do this. XMLHttpRequest is a host object and you should not try to extend it. To quote Kangax:

Next problem with DOM extension is that DOM objects are host objects, and host objects are the worst bunch. By specification (ECMA-262 3rd. ed), host objects are allowed to do things, no other objects can even dream of. To quote relevant section [8.6.2]:

Host objects may implement these internal methods with any implementation-dependent behaviour, or it may be that a host object implements only some internal methods and not others.

This also means that host objects may disallow extension by using prototype.

However, as Kangax also advices, you can create a wrapper around XMLHttpRequest and do whatever you like with it.

Upvotes: 8

Related Questions