Search code examples
javascriptextend

Overwrite a function in a function


I am trying to figure out how to extend :

var outdatedBrowser = function(options) {
  function startStylesAndEvents() {
   console.log("bleh");
  }
}

I am trying to overwrite the function startStylesAndEvents without touching the source code of the library : https://github.com/burocratik/outdated-browser/blob/develop/outdatedbrowser/outdatedbrowser.js

So when I call:

outdatedBrowser({
    bgColor: '#f25648',
    color: '#ffffff',
    lowerThan: 'transform',
    languagePath: 'your_path/outdatedbrowser/lang/en.html'
})

and it uses the startStylesAndEvents function, it uses mine instead of theirs...

Thanks!


Solution

  • Without modifying the original source? You can't.

    All of JavaScript scoping is based on functions (ignoring let, const and class for the moment). If a value is declared inside of a function, it cannot be accessed outside of that function unless it is returned from the function or modifies some external value.

    For example, imagine a function like this:

    function doStuff() {
      var times = 10;
      for (var i = 0; i < times; i++) {
        doThing(i);
      }
    }
    

    Your question is semantically identical to asking how to change times. It just can't be done.