如何创建XMLHttpRequest包装器/代理?

tlr*_*son 7 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
        return _open.apply(this, arguments);
    }

    return xhr;
}
Run Code Online (Sandbox Code Playgroud)

方法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);
}
Run Code Online (Sandbox Code Playgroud)

方法3:完全代理本机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);
}
Run Code Online (Sandbox Code Playgroud)

use*_*621 2

根据 JS 引擎,方法 1 会产生相当大的开销,因为xhr.open每当 XHR 实例化时都会重新定义。

new _XMLHttpRequest方法2让我思考“为什么你首先需要它”?虽然有轻微的副作用,但似乎效果很好。

方法3:简单、老派,但不会立即起作用。(思考阅读属性)

一般来说,我个人不愿意覆盖浏览器对象,因此这对所有三种方法来说都是一个很大的缺点。最好使用其他一些变量,例如ProxyXHR(只是我的 2 美分)