It's usually to namespace (see later) and control the visibility of member functions and/or variables. Think of it like an object definition. jQuery plugins are usually written like this.
In Javascript, you can nest functions. So, the following is legal:
function outerFunction() {
function innerFunction() {
// code
}
}
Now you can call outerFunction()
, but the visiblity of innerFunction()
is limited to the scope of outerFunction()
, meaning it is private to outerFunction()
. It basically follows the same principle as variables in Javascript:
var globalVariable;
function someFunction() {
var localVariable;
}
Correspondingly:
function globalFunction() {
var localFunction1 = function() {
//I'm anonymous! But localFunction1 is a reference to me!
};
function localFunction2() {
//I'm named!
}
}
In the above scenario, you can call globalFunction()
from anywhere, but you cannot call localFunction1
or localFunction2
.
What you're doing when you write (function() { ... code ... })()
, is you're making the code inside a function literal (meaning the whole "object" is actually a function). After that, you're self-invoking the function (the final ()
). So the major advantage of this as I mentioned before, is that you can have private methods/functions and properties:
(function() {
var private_var;
function private_function() {
//code
}
})()
The neat thing is that you can also define things inside and expose it to the outside world so (an example of namespacing so you can basically create your own library/plugin):
var myPlugin = (function() {
var private_var;
function private_function() {
}
return {
public_function1: function() {
},
public_function2: function() {
}
}
})()
Now you can call myPlugin.public_function1()
, but you cannot access private_function()
! So pretty similar to a class definition. To understand this better, I recommend the following links for some further reading:
EDIT
I forgot to mention. In that final ()
, you can pass anything you want inside. For example, when you create jQuery plugins, you pass in jQuery
or $
like so: (function(jQ) { ... code ... })(jQuery)
. So what you're doing here is defining a function that takes in one parameter (called jQ
, a local variable, and known only to that function). Then you're self-invoking the function and passing in a parameter (also called jQuery
, but this one is from the outside world and a reference to the actual jQuery itself). This is because everything you define inside is effectively inside the function. So if you need to know about anything from the outside world, you need to pass it in.