Javascript 如何创建XMLHttpRequest包装器/代理?
想到这些方法,每种方法的优缺点是什么 方法1:增强本机实例Javascript 如何创建XMLHttpRequest包装器/代理?,javascript,xmlhttprequest,Javascript,Xmlhttprequest,想到这些方法,每种方法的优缺点是什么 方法1:增强本机实例 var _XMLHttpRequest = XMLHttpRequest; XMLHttpRequest = function() { var xhr = new _XMLHttpRequest(); // augment/wrap/modify here var _open = xhr.open; xhr.open = function() { // custom stuff
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
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);
}
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);
}
方法3:本机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);
}
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
方法2让我想到“为什么首先需要新的\u XMLHttpRequest
”?有一点不希望的副作用,但它似乎工作得很好
方法3:简单,老派,但它不会马上奏效。(想想阅读属性)
一般来说,我个人不太愿意覆盖浏览器对象,所以这对所有三种方法都是一个很大的弊病。最好使用一些其他变量,如
ProxyXHR
(仅2美分)它可能取决于用例。在我的例子中,我想创建一个完整的代理,这似乎只有使用第三种方法才能实现。问题是需要在原始XHR实现上设置onreadystatechange
。我想有一些getter和setter是不能从外部更改的
由于此原因,方法1和2将不起作用。为了实现这一点,我写了一个完整的,也就是说我没有发现任何bug的XHR代理:。这需要使用方法3来完成。使用下面的配置
\u XMLHTTPRequest.setProxy(proxySetting、varProxyServer、varBypassList)代码>
参数详情:
代理设置-代理配置
例如:SXH_PROXY_SET_DEFAULT、SXH_PROXY_SET_DIRECT、SXH_PROXY_SET_PROXY、SXH_PROXY_SET_Prefig
varProxyServer-代理服务器的名称
varBypassList—要允许绕过代理服务器的主机名或IP地址。我已尝试了所有3种方法。我必须截取代码中的调用,我不管理这些代码,这些代码已经运行了Boomerang AutoXHR插件并截取调用#2和#3只是导致了错误,但#1在我奇怪的混乱用例中工作得非常好。最简单的方法就是简单地使用(或任何其他JavaScript框架)。我觉得你的第一种方法是错误的。我担心在堆栈溢出之前,您将陷入递归循环。;)你为什么想要这个?有很多更简洁的解决方案,它们不必提供对引用对象的函数调用。Marcel:你说得对,这是一种类型,我已经解决了。ThiefMaster:我的大多数问题都没有得到充分的回答……使用方法3,我得到一个错误TypeError:object[object object]没有方法“setRequestHeader”