如何创建XMLHttpRequest包装器/代理? [英] How can I create a XMLHttpRequest wrapper/proxy?

查看:234
本文介绍了如何创建XMLHttpRequest包装器/代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想到这些方法,每种方法的优缺点是什么?

These methods that come to mind, what are the pros and cons of each?

方法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;
}

方法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);
}

方法3:原生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包装器/代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆