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?
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?
Share Improve this question edited Feb 13, 2014 at 22:17 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Jun 4, 2010 at 15:58 Ravish BhagdevRavish Bhagdev 9551 gold badge13 silver badges27 bronze badges 1- I found a function that can be used to generate a list of conflicting function names for two objects. stackoverflow.com/a/15330156/975097 – Anderson Green Commented Mar 11, 2013 at 2:11
3 Answers
Reset to default 17The 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.
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:
- Namespacing your JavaScript
- JavaScript Namespacing
A second function declaration for the same function name overwrites an earlier one, so it will depend on the order your scripts are included.