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

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

问题描述

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

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)

这篇关于如何创建 XMLHttpRequest 包装器/代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)