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);
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With