How to share functions between javascript files?

2

I have two JavaScript files.

file1.js

function teste()
{
alert("fui chamado!");
}

In file2.js I would like to have access to the teste() function of file1.js without having to reference within HTML . Home Is this possible?

    
asked by anonymous 02.06.2015 / 23:03

2 answers

4

You can dynamically load the script by creating a script tag and inserting it into the page. For example:

File1.js

function Script1() {
    this.DigaOla = function() {
        alert("Sou do script 1");
    }
};

File2.js

 function loadScript(url, callback) {    
     var head = document.getElementsByTagName('head')[0];
     var script = document.createElement('script');
     script.type = 'text/javascript';
     script.src = url;    
     script.onreadystatechange = callback;
     script.onload = callback;

     head.appendChild(script);
 }

 $(document).ready(function() {
    loadScript("Arquivo1.js", function() {               
        var s = new Script1();
        s.DigaOla();
    });
 });
    
03.06.2015 / 00:30
4

The simplest way is to include file1 before file2 in your HTML:

<!doctype html>
<html>
<head>
    <script src="arquivo1.js"></script>
    <script src="arquivo2.js"></script>
</head>

All globals defined in file1 will be visible in file2.

A slightly cleaner way to do this is to write the file1 so that only one global one is exported:

var LIB = {};

(function(){

   var msg = "fui chamado";

   var funcao_interna(){
       alert("oi");
   }

   LIB.teste = function(){
       alert(msg);
   }

   LIB.teste2 = funcao_interna;
}());

And in file2 you do

LIB.teste();

This (function(){ ... }()) is a "function immediately invoked" and is a trick that is used in Javascript to control the scope of the variables. All variables and functions declared therein, such as msg and funcao_interna will not be visible from the outside.

Another way you can write is like this:

var LIB = (function(){

    function teste(){ alert("chamou") }

    return {
       teste:teste
    }
}());
    
02.06.2015 / 23:50