Possible Duplicate:
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
Hello all,
I have seen several JavaScript files using this notation:
Start of JavaScript file:
(function() {
// All functions go here.
// Can someone say what the wrapping nameless function is used for?
})();
Also with the prototype library, this seems possible:
function $() {
// Prototype $-wrapping function.
}
Can someone please explain the above two code fragments, their uses and their differences? Some keywords which would help me find more about this notation/technique (how it is named) would be helpful too so I can run a Google search on it… 🙂
Thanks!
In your first example, people surround their code in an anonymous function for scoping reasons, to avoid global namespace cluttering. That weird parentheses syntax is used to define and execute the function all in one step; the
()at the end has the meaning of executing the function itself.So inside that anonymous function you could define
function apple(){}and it would only be accessible inside that anonymous function. This is good if you’re making a library and want only certain things to clutter your global namespace.Your second example is just a simple function called
$. Many libraries like to use this name because it’s short and concise, and since you need to type it every time you want to reference the libraries namespace, the shorter, the better.