My first answer tried to solve your original questions and show how to set up a namespace. Instead of adding to this answer, I decided to add a second answer to answer the questions in your comment on my first answer.
Global variables are really properties of the window object. If you use var outside the function, you define a global variable. If you use var inside a function, you define a local variable. If you reference the variable someValue without declaring it with var , it matches the link window.someValue .
The following code shows various ways to set a global variable and one way to define a local variable.
window.global1 = 'abc'; global2 = 'def'; var global3 = "ghi"; (function() { window.global4 = 'jkl'; global5 = 'mno'; var local1 = 'xyz'; })(); console.log(global1); // 'abc' console.log(global2); // 'def' console.log(global3); // 'ghi' console.log(global4); // 'jkl' console.log(global5); // 'mno' console.log(local1); // ReferenceError: local1 is not defined
In general, you want to limit the setting of global variables (at least when creating the JavaScript library). A namespace is just a global variable. When you place everything else in this namespace, you have added only one global variable.
I think it is also better to avoid setting global variables like global2 and global5 above. Instead, you should use var oustide functions (e.g. global3 ) or set a property in a window object (e.g. global1 and global4 ).
Borrowing sample code from my other answer, we can create a namespace like this:
var myApp = (function() { var privateValue = 'abc';
We could achieve the same by doing the following, but I find this bad style:
(function() { var privateValue = 'abc';
In both cases, we set the global variable myApp , but I think it is much clearer in the first than in the last.
To be clear, in both cases we will consider the public variable as myApp.publicValue and call the public function using myApp.publicFunction() , and outside of the anonymous function we will not be able to refer to privateValue or privateFunction .