想到的这些方法,各有什么优缺点?
These methods that come to mind, what are the pros and cons of each?
方法一:增强原生实例
var _XMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function() {
var xhr = new _XMLHttpRequest();
// augment/wrap/modify here
var _open = xhr.open;
xhr.open = function() {
// custom stuff
return _open.apply(this, arguments);
}
return xhr;
}
方法2:子类"原生XMLHttpRequest
Method 2: Sub-"class" native XMLHttpRequest
var _XMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function() {
// definePropertys here etc
}
XMLHttpRequest.prototype = new _XMLHttpRequest());
// OR
XMLHttpRequest.prototype = Object.create(_XMLHttpRequest);
// custom wrapped methods on prototype here
XMLHttpRequest.prototype.open = function() {
// custom stuff
return _XMLHttpRequest.prototype.open.apply(this, arguments);
}
方法三:完全代理原生 XMLHttpRequest
Method 3: Full proxy to native XMLHttpRequest
var _XMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function() {
this.xhr = new _XMLHttpRequest();
}
// proxy ALL methods/properties
XMLHttpRequest.prototype.open = function() {
// custom stuff
return this.xhr.open.apply(this.xhr, arguments);
}
根据 JS 引擎,方法 1 会产生相当大的开销,因为每当实例化 XHR 时都会重新定义 xhr.open.
Depending on the JS engine, method 1 produces considerable overhead, since xhr.open is redefined whenever XHR is instantiated.
方法 2 让我想为什么首先需要 new _XMLHttpRequest"?有轻微副作用的感觉,但似乎效果很好.
Method 2 makes me think "why would you need the new _XMLHttpRequest in the first place"? There's a minor feeling of undesired side effects, but it appears to work just fine.
方法 3:简单、老派,但不会立即奏效.(考虑读取属性)
Method 3: simple, old-school, but it won't work straight-away. (Think about reading properties)
一般来说,我个人不太愿意覆盖浏览器对象,所以这对所有三种方法来说都是一个很大的缺点.最好使用其他变量,例如 ProxyXHR(只是我的 2 美分)
In general, I'm personally reluctant when it comes to overwriting browser objects, so that would be a big con to all three methods. Better use some other variable like ProxyXHR (just my 2 cents)
这篇关于如何创建 XMLHttpRequest 包装器/代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
即使在调用 abort (jQuery) 之后,浏览器也会等待Browser waits for ajax call to complete even after abort has been called (jQuery)(即使在调用 abort (jQuery) 之后,浏览器也会等待 ajax 调用
JavaScript innerHTML 不适用于 IE?JavaScript innerHTML is not working for IE?(JavaScript innerHTML 不适用于 IE?)
XMLHttpRequest 无法加载,请求的资源上不存在“AXMLHttpRequest cannot load, No #39;Access-Control-Allow-Origin#39; header is present on the requested resource(XMLHttpRequest 无法加载,请求的资
XHR HEAD 请求是否有可能不遵循重定向 (301 302)Is it possible for XHR HEAD requests to not follow redirects (301 302)(XHR HEAD 请求是否有可能不遵循重定向 (301 302))
NETWORK_ERROR:XMLHttpRequest 异常 101NETWORK_ERROR: XMLHttpRequest Exception 101(NETWORK_ERROR:XMLHttpRequest 异常 101)
XMLHttpRequest 206 部分内容XMLHttpRequest 206 Partial Content(XMLHttpRequest 206 部分内容)