Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 280
Ravish Bhagdev Avatar asked Jun 04 '10 15:06

Ravish Bhagdev


People also ask

Can you have two functions with same name JavaScript?

JavaScript supports overriding not overloading, meaning, that if you define two functions with the same name, the last one defined will override the previously defined version and every time a call will be made to the function, the last defined one will get executed.

What is function ($) in JavaScript?

(function($) { // do something })(jQuery); this means, that the interpreter will invoke the function immediately, and will pass jQuery as a parameter, which will be used inside the function as $ .

Can a function and a variable have the same name JavaScript?

Variables and functions share the same namespace in JavaScript, so they override each other. if function name and variable name are same then JS Engine ignores the variable. With var a you create a new variable. The declaration is actually hoisted to the start of the current scope (before the function definition).

Is not a function TypeError JavaScript?

A TypeError: "x" is not a function occurs when a function is called on an object that does not contain the called function. When calling a built-in function that expects a callback function argument, which does not exist. When the called function is within a scope that is not accessible.


1 Answers

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.

like image 56
SLaks Avatar answered Nov 03 '22 01:11

SLaks