Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript notation: (function() { ... } )(); [duplicate]

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!

like image 410
Sander Avatar asked Mar 10 '11 08:03

Sander


4 Answers

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.

like image 132
Luca Matteis Avatar answered Sep 28 '22 09:09

Luca Matteis


I searched for "javascript wrapping function" and the first hit was this, which says:

This method doesn't add any new symbols to the global or LIB spaces.

I don't understand the second part of the question: function $() { ... } isn't a "nameless" function: it has the name $! If you like functions named $ it's the most straightforward way I know of to make such a thing.

like image 28
Ken Avatar answered Sep 28 '22 11:09

Ken


An annonymous function is defined

function() {
}

and then immediately called

()

The extra () enclosing the function is to force the interpreter to treat the function as an expression. Javascript treats any statement starting with the function keyword as a declaration so it could not otherwise be immediatly called.

The purpose is to avoid polluting the global namespace. All variables defined in the function will be local to the function.

Google for module pattern.

like image 34
river Avatar answered Sep 28 '22 11:09

river


retracted in favor of answer to: What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

like image 31
necromancer Avatar answered Sep 28 '22 09:09

necromancer