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?
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.
(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 $ .
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With