How to call Javascript functions in another Javascript

4

I wanted to call a function from a Javascript in another Javascript file.

For example, in the calculate.js file, I have the function add (a, b) . And I needed to call this function in the calculator.js file (for example).

I was wondering if this communication between two or more js files is possible. And how could it be done?

    
asked by anonymous 23.07.2014 / 13:54

3 answers

7

Your first Javascript should create the function in the global scope, using window. :

var window.somar = function(a, b) {
  // código aqui
};

So it becomes visible in the other file as long as it is included first:

<script src="calcular.js"></script>
<script src="calculadora.js"></script>
    
23.07.2014 / 14:11
3

The functions that you load in the global scope can be used in any script that loads in the sequence. This is for both inline javascript and included.

You can also have the first script execute an existing function in the second script, but this should trigger the execution of the onload event of the document as this example (using jQuery):

$(document).ready(function() {
   somar(a,b); //somar() ainda será definido
});
    
23.07.2014 / 14:22
0

Only place:

window.parent.nomedafuncao();

Example:

window.parent.sw(‘teste’);
    
28.11.2018 / 15:01