Can I create a new proxy?

What's the best way to create an 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); }

  • Answer:

    The best way to create any "wrapper", "proxy" or "polyfill" is to NEVER OVERWRITE NATIVE OR HOST OBJECTS. The best practice is create your own namespace that will store all of your wrapper/proxy/polyfills. The absolute, most basic example of this practice: (function ( global ) { function XHR() { if ( global.XMLHttpRequest ) { // return standards XHR object return new global.XMLHttpRequest(); } // return IE XHR object return new global.ActiveXObject("Microsoft.XMLHTTP"); }; global.XHR = XHR; })( this ); var xhrConnection = XHR(); console.log( xhrConnection ); // > XMLHttpRequest Object And just to note, your first example attempts to reference the original XMLHttpRequest from within the redefinition, instead of the copied reference "_XMLHttpRequest" - which will throw a RangeError callstack exceeded exception. Consider the new information given in the comments, if you absolutely MUST overwrite the host object, then I would start by implementing the host's properties and prototype methods. This would be a good model: And I would just go with method three, full proxy/duck-punch.

Rick Waldron at Quora Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.