driima
driima

Reputation: 643

Modify existing nested JavaScript function

Let's say a web page has the following code loaded from an external JavaScript file:

(function(foo) {
    function bar() {
        // Do something
    }

    function baz() {
        // Do something else
    }
})(window, window.jQuery);

For arguments sake, let's say I'm writing a chrome extension that will load a script I created with changes to some of the existing code; perhaps changes to the bar function but not baz. I could copy all of the existing code, make my changes, and load the modified JavaScript after blocking the original, but I don't want to do that if I can avoid it.

Is there a way to modify the behaviour of existing nested functions without loading a whole copy of the modified code?

Upvotes: 1

Views: 39

Answers (1)

Xan
Xan

Reputation: 77482

Not really, no.

This pattern, an immediately-invoked anonymous closure:

(function() {
  // stuff
})();

is specifically used to hide the internal contents from the global namespace. Once that code finishes executing, there are no references that can access its internal contents.

So your plan of blocking the script and then providing your full copy seems to be the only one you can do.

Upvotes: 1

Related Questions