Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 811
Anil Namde Avatar asked Feb 26 '23 04:02

Anil Namde


1 Answers

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.

like image 147
Marcel Korpel Avatar answered Mar 07 '23 19:03

Marcel Korpel