問題描述
想到的這些方法,各有什么優(yōu)缺點?
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);
}
推薦答案
根據(jù) JS 引擎,方法 1 會產(chǎn)生相當(dāng)大的開銷,因為每當(dāng)實例化 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)
這篇關(guān)于如何創(chuàng)建 XMLHttpRequest 包裝器/代理?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!