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?

1

3 Answers 3

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.

0
2

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:

1
  • Yes, but he cannot modify the scripts.
    – SLaks
    Commented Jun 4, 2010 at 16:03
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.