By default, all variables (and therefore function declarations) live in the global namespace.
The only way to introduce a separate namespace in javascript is to call a function. Here's how you do it:
(function () { }());
You end your material with an anonymous function, and then call it immediately. Thus, your functions will be separate, even with the same name.
Example
So, for example, if you have a code like this:
var my, local, data; function initData() { // use my, local and data here. }
and you have somewhere else:
var some, other, data; function initData() {
then one initData overwrite another initData . However, if you wrap each one in its own (function () {}()); then they will be separate.
(function () { var my, local, data; function initData() {
Keep in mind that these names are no longer in the global namespace, therefore they are also not available for use outside of an anonymous function.
One global
To control how much and what you open in the global namespace, the user can expose everything you need through one global object, usually with all capital letters.
FOO.module1.initData(); FOO.module2.initData();
You would do this by making sure that FOO exists, and if not: create it.
var FOO = this.FOO || {};
Same thing for module namespaces:
FOO.module1 = FOO.module1 || {};
and then inside the anonymous function, show what you want.
Full example
module1.js:
var FOO = this.FOO || {}; FOO.module1 = FOO.module1 || {}; (function () { var my, local, data; function initData() {
module2.js:
var FOO = this.FOO || {}; FOO.module2 = FOO.module2 || {}; (function () { var some, other, data; function initData() {
controller.js:
FOO.module1.initData(); FOO.module2.initData();
Last tip
The controller, like the recorded one, depends on both module1.js and module2.js and should be loaded last. This can be avoided by using something like jQuery document.ready , making it wait for all scripts to load.
jQuery(document).ready(function () { FOO.module1.initData(); FOO.module2.initData(); });
If you are not using jQuery yet, you can use a small script like domReady to avoid bloating.