0

I am having a hard time understanding how this preserves a function an essentially extends it.

I see that (function(){}) will call a declared function immediately. I don't understand what supplying open as a parameter. Finally, I don't understand what goes on with (XMLHttpRequest.prototype.open). Is this calling the prototype function?

(function(open) {
  XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
    open.call(this, arguments);
  };
})(XMLHttpRequest.prototype.open);

2 Answers 2

2

function (open) { .. } declares a function which takes one argument.
(..)(XMLHttpRequest.prototype.open) is calling this function and is passing the open function of XMLHttpRequest.prototype as argument. Yes, it's passing the actual function itself; functions can be passed around like values.

So, inside that IIFE (immediately invoked function expression), open is the original implementation of XMLHttpRequest.prototype.open.

Then, inside the IIFE, XMLHttpRequest.prototype.open gets replaced with a new function. Inside that new function, the original open function gets called. This by itself isn't too exciting, but it shows how you could wedge in your own code between XMLHttpRequest.prototype.open being called and the actual, original open function being executed.

The whole ordeal with the IIFE is just to preserve a handle to the original open function which cannot be overwritten by other code under any circumstances, because it's local to a function.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I just am still stuck on (function (param){})(myParam). How can myParam be passed to the function? (function())() What is this called?
It's called an IIFE.
If that makes it easier, rewrite it as function foo(open) { .. }; foo(XMLHttpRequest...);. Same thing.
1

This is exact replica of this.

//Create a XMLHttpRequest.realOpen function and store the original XMLHttpRequest.open function in it
XMLHttpRequest.prototype.realOpen = XMLHttpRequest.prototype.open;

//Change the XMLHttpRequest.open function
XMLHttpRequest.prototype.open = function(method, url, async, user, password) {

    //Do Your Code Here....

    //Call original XMLHttpRequest.open function which is now saved in XMLHttpRequest.realOpen function
    this.realOpen(method, url, async, user, password);
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.