How to extend XMLHttpRequest object in JavaScript?

走远了吗. 提交于 2019-12-30 07:33:31

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/4931977/how-to-extend-xmlhttprequest-object-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!