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

2022-01-15 00:00:00 xmlhttprequest javascript

想到的这些方法,各有什么优缺点?

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)

相关文章