9

I have two external JavaScript lib files I have to load on same JSP page. They both have a function called "autoSave()", both without parameters. I cannot modify their signature as they are not my script files.

How can I call a function in script A or script B explicitly? How is the precedence decided?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ravish Bhagdev
  • 955
  • 1
  • 13
  • 27
  • I found a function that can be used to generate a list of conflicting function names for two objects. http://stackoverflow.com/a/15330156/975097 – Anderson Green Mar 11 '13 at 02:11

3 Answers3

17

The function defined by the second script will overwrite the function defined by the first one.

You can save a copy of the function from script A before including script B.

For example:

<script type="text/javascript" src="Script A"></script>
<script type="text/javascript">
    var autoSave_A = autoSave;
</script>

<script type="text/javascript" src="Script B"></script>
<script type="text/javascript">
    var autoSave_B = autoSave;
</script>

Note, by the way, that if script A calls autoSave by name, the script will call the wrong autoSave and (probably) stop working.
You could solve that by swapping in the autoSave functions before calling functions from either script using wrapper methods.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

Well, IMO your libraries should be namespaced, so you could easily call lib1.autoSave() or lib2.autoSave(arg).

The goal is to use as few global variables as possible.

Give a look to the following articles:

Community
  • 1
  • 1
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
0

A second function declaration for the same function name overwrites an earlier one, so it will depend on the order your scripts are included.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928