Reputation:
I've several JS files; the first one is a library to be used by the next ones, and every one of those another files have a function main() which calls the functions of that file.
lib.js => library
a.js :: main() => call functions in a.js
b.js :: main() => call functions in b.js
...
...
So, I would want that were run the function main for those files (after of loading lib.js).
How do run each function main after of loading the JS file?
It would be load a.js and run main, load b.js and run main, ...
Upvotes: 2
Views: 96
Reputation: 9202
JavaScript is not C or something similar.
It doesn't matter in which file you define the function. The function will be overwritten.
So if you first load the file a.js
and then the file b.js
The main
function will be the main
function which you've defined in b.js
and the main
function you've defined in a.js
won't exists anywhere.
If you want to keep old functions I recommend you to create an object in each file and define the main function in it. So something like this.
a.js
:
var a = {};
a.main = function() {
/* do stuff */
};
b.js
:
var b = {};
b.main = function() {
/* do stuff */
};
So now you can call:
a.main();
and
b.main();
Upvotes: 2
Reputation: 11613
If you need to control the dependencies (order of load), use something like head.js
or require.js
.
However, don't pollute your global namespace by reusing the global function name main
in all of your JS files. There's plenty of documentation on the web about how to avoid polluting global namespace and why it's a good idea. It's an easy web search.
More info in the answers here: How do I declare a namespace in JavaScript?
Upvotes: 1