How do I execute a main() function without affecting the other of another script?

Asked

Viewed 32 times

-2

I have three files:

Arquivo1.js

function main() {
    . . .
}

Arquivo2.js

function main() {
    . . .
}

System js

function openApp(package) {
    var a = document.createElement("script");
    a.src = "/" + package + "/Arquivo1.js";
    document.body[0].appendChild(a);
}

How do I call main() of Arquivo1 without affecting the main() of Arquivo2 inside the System file, which is the head...

I’ve written this post on the original stackoverflow, but no one answered...

EDIT: I updated the code, I want everything to be standardized!

1 answer

0

One way out is to not pollute the global namespace by encapsulating the functions of each file into a prototype. In this case, the Arquivo1becomes:

Arquivo1.js

function Arquivo1() {
    this.main = function() {
        return 'A1'
    }
}

Similarly to the Arquivo2. Now the functions are isolated, each in its own prototype. Now, in the main file, we can do:

System js

arquivo1 = new Arquivo1()
arquivo2 = new Arquivo2()
valorDaMainDoArquivo1 = Arquivo1.main()
valorDaMainDoArquivo2 = Arquivo2.main()
  • And as I do this a system of Packages, identical to android, well, I have a function that records the Avascripts by folders, if the package is "a.a.a", the folder will be a.a.a/js/main.js, and would have to be standard for all files, because the system is within a function...

  • Then in that case I would have to write package + Arquivo1.main?

  • Well, I think I understand your problem correctly. The System is responsible for adding the functions to the html file and you access these functions later, correct?

  • Yes, exact.....

  • Well, in that case I would recommend you to use modules: https://developers.google.com/web/fundamentals/primers/modules#browser, or use a bundler to compile all your code in one file, such as Webpack https://webpack.js.org/

Browser other questions tagged

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