Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

javascript - How can I create a XMLHttpRequest wrapper/proxy?

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

Method 1: Augment native instance

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

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

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Depending on the JS engine, method 1 produces considerable overhead, since xhr.open is redefined whenever XHR is instantiated.

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.

Method 3: simple, old-school, but it won't work straight-away. (Think about reading properties)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...