The ()
that wrap the function turns the anonymous function declaration into a function expression that can then be immediately invoked with the ()
that follows the expression.
In this case, the outer ()
really isn't necessary since the var foo =
would turn it into an expression. Also, the value of foo
will be undefined
since the function invocation doesn't return anything.
It can be used for creating a new variable scope, since a function is the only way to accomplish that in javascript. (Javascript doesn't have block scope.)
So the someVar
variable is not accessible to the outer scope. There may be times when it is desirable to make it accessible in a controlled manner. To do this, you can pass a function out of that scope which references someVar
. Then after the function invocation exits, its execution context will remain intact, and someVar
will be available in whatever manner the function you passed out provides.
This is called creating a closure
.
Let's say you passed a value into the invocation, and assigned it to someVar
. You could then return
a function out of the invocation to the foo
variable. If that function you return references someVar
, then you could use that function to get its value.
var foo = (function ( str ) {
var someVar = str;
/*
function someFunc() {
return true;
}
*/
return function() {
alert( someVar );
};
})( 'somevalue' );
foo(); // alerts 'somevalue'
As you can see, the function now referenced by foo
can still access someVar
.
Let's say you changed it so that the function returned to foo
can accept an argument, which will update the value of myVar
.
var foo = (function ( str ) {
var someVar = str;
/*
function someFunc() {
return true;
}
*/
return function( n ) {
if( n ) {
someVar = n;
} else {
alert( someVar );
}
};
})( 'somevalue' );
foo(); // alerts 'somevalue'
foo( 'newvalue' ); // give it a new value
foo(); // alerts 'newvalue'
Now you can see, that the function in foo
really does access that variable, as it is able to change its value, and reference the new value that it previously set.