How to deal with conflicting function names in JavaScript if functions are from external JavaScript libraries?

I have two external javascript javascript files that I have to load on the same JSP page. Both of them have a function called "autoSave ()", with no parameters. I cannot change my signature as they are not my script files.

How can I explicitly call a function in script A or script B? How is the decision made?

+4
source share
3 answers

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

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

For instance:

<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 that if script A calls autoSave by name, the script calls the wrong autoSave and (possibly) terminates.
You can solve this by replacing autoSave functions before calling functions from a script using wrapper methods.

+13
source

Well, in IMO, your libraries should be placed in names, so you can easily call lib1.autoSave() or lib2.autoSave(arg) .

The goal is to make the most of as multiple global variables .

Take a look at the following articles:

+1
source

Declaring a second function for the same function name overwrites the earlier version, so it will depend on the order in which your scripts are included.

0
source

Source: https://habr.com/ru/post/1311883/


All Articles