How to call Javascript functions in another Javascript

Asked

Viewed 7,761 times

4

I wanted to call a Function of a Javascript in another Javascript file.

For example, in the file compute js., i have the Function sum(a,b). And I needed to call this Function in the file js calculator. (for example).

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

3 answers

9


Your first Javascript should create the function in the global scope, through 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>
  • 7

    Correct. But you don’t need to explicitly write window.somar. var somar = function(a,b) or function somar(a, b) also work.

  • 2

    No need to inform window if you are in the global scope of a single document

  • 2

    @Beet Yes, but let’s say that this is the most "safe" way, because if you declare this function within the scope of another, it does not become visible (if you are using this approach, for example).

  • And guys, thanks for the help, it helps me a lot. Thank you.

4

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

You can also make the first script execute an existing function in the second script, but to do so you must trigger the event execution onloaddocument as this example (using jQuery):

$(document).ready(function() {
   somar(a,b); //somar() ainda será definido
});
  • Thanks for the help. Thanks :)

0

Just put:

window.parent.nomedafuncao();

Example:

window.parent.sw(‘teste’);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.