The simplest way is to include archive1 before archive2 in your HTML:
<!doctype html>
<html>
<head>
<script src="arquivo1.js"></script>
<script src="arquivo2.js"></script>
</head>
All globes defined in archive1 will be visible in archive2.
A slightly cleaner way to do this is to write archive1 so that only a 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 file 2 you do
LIB.teste();
That one (function(){ ... }())
is an "immediately invoked function" and is a trick that is used in Javascript to control the scope of variables. All variables and functions declared inside, such as msg
and funcao_interna
shall not be visible from outside.
Another way you can write is like this:
var LIB = (function(){
function teste(){ alert("chamou") }
return {
teste:teste
}
}());
You can use a module manager such as Requirejs. This will require you to change file 1 to make it compatible.
– bfavaretto
Similar or duplicated to: http://answall.com/q/63389/129 ?
– Sergio
Sorry @Sergio but the link you showed is a good alternative for those who want to create a universal variable for example, but in my case, I want to be able to control which file will have access to the functions of the other.
– Jedaias Rodrigues
@bfavaretto you would have some example of use in English?
– Jedaias Rodrigues
I have nothing to recommend, but Google brings several tutorials. This one looks like one of the most complete: http://www.devmedia.com.br/standardizca-com-iife-amd-e-requirejs/31031 (warning: I have not read, I do not guarantee the quality).
– bfavaretto
By not referencing in HTML you delete the possibility to create the reference dynamically? You can add the script arquivo1.js creating a tag
<script>
in the arquivo2.js and dynamically insert it into the page.– Marcus Vinicius
@Marcusvinicius This is possible, but it is necessary to wait for the other file to load before having access to the functions inside it (the loading is asynchronous).
– bfavaretto
Yes, @bfavaretto. It is possible to make one script "wait" for the other using callbacks in the event
onload
of the created script element.– Marcus Vinicius
@Marcusvinicius By the way, that’s basically what Requirejs does :)
– bfavaretto
@Jedaiasrodrigues: a while ago I "hunted" the function inside the other file via xmlhttprequest using an intermediary php that returned the function as String to be executed as code. At the time I had compatibility problems, maybe things are better today. It will be a great resource to develop in Javascript background!
– Gustavo
Thank you all for your help, I really liked the reply posted by @Marcusvinicius but unfortunately now I have problems precisely in the issue of asynchronous.
– Jedaias Rodrigues