0

I have a seemingly large problem at hand. I have a Javascript file, let's call it helloworld.js. I can't edit that file at all. However, inside, there's a function named function buildDropdown(){}.

I need to be able to make changes to that function only without editing the file. I can add another .js file after or before the helloworld.js file loads. I am guessing there must be a way to write patch .js file to overrides function buildDropdown(){}. Is there an easy way in js to tell it to ignore the previous function buildDropdown(){} and use my function buildDropdown(){} that overrides it?

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Hello Universe
  • 3,248
  • 7
  • 50
  • 86
  • 4
    The last defined function will be the final version. – MaxZoom Apr 20 '15 at 01:37
  • 1
    there are answers out there, a quick google would've gotten you these http://stackoverflow.com/questions/296667/overriding-a-javascript-function-while-referencing-the-original http://stackoverflow.com/questions/19301516/override-js-function-from-another-file – Abdul Ahmad Apr 20 '15 at 01:37

3 Answers3

1

Just define yours after the original. Assuming you don't need to keep anything in the original. If you do . . . like if you need to wrap it in something else for example, you can do something like this:

var origBuildDropdown = buildDropdown;
function buildDropdown() {
  // Do pre-function stuff

  // Invoke original function
  origBuildDropdown();

  // Do post-function stuff
}
tandrewnichols
  • 3,456
  • 1
  • 28
  • 33
1

You can just define the function again, it will overwrite the previously defined function:

<script src="helloworld.js">
    function buildDropdown(){
        /* Old Function */
    }
</script>
...
<script src="yourScript.js">
    function buildDropdown(){
        /* New code here */
    }
</script>
Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
1

Several answers have already explained how to do what you want, but it seems worth explaining WHY.

Every javascript function you (or some random script file you load) define is just an object. It's a variable declaration. As such, it's subject to being redefined at runtime. You can, for that matter, do so dynamically...self-modifying code is entirely possible, though that doesn't mean it's often a good idea.

Like any other variable declaration, functions have scope - which makes perfect sense, once you start thinking about them as variables. Depending on where your black-box file is defining the function you need, you might need to go a few layers deep into the structure of some object to redefine it. But it can be done.

S McCrohan
  • 6,663
  • 1
  • 30
  • 39