Search code examples
javascriptmonkeypatching

How to monkey-patch a function declared inside another function


Say I have the following code:

window.foo = function() {
  bar();
  function bar() {
    console.log('hello');
  }
}
/* insert monkey-patching code here */
foo();

What code can I replace /* insert monkey-patching code here */ with in order to make this e.g. write goodbye instead of hello on the console?

I have tried the following in order to override bar, but it does not work:

window.foo = function() {
  bar();
  function bar() {
    console.log('hello');
  }
}
window.bar = function() {
  console.log('goodbye');
}
window.foo.bar = function() {
  console.log('goodbye');
}
foo();

Solution

  • You can't.

    The function is stored in a local variable inside foo. It isn't accessible from outside that function.

    You would need to either:

    • Replace the whole of foo
    • Refactor foo so bar was declared in a wider scope (and accessible from where you want to change it)