GPGVM
GPGVM

Reputation: 5619

Why would a javascript function be wrapped as anonymous

In reading a technical education post I came across this sample code from the author..sterilized of course. The content of the functions is not what I found curious and everything worked as the author had described.

What caught me was wrapping the function in an anonymous (I think that's what they did) function. The only thing I can see with my meager knowledge is that it creates a grouping/container.

Why is this and should I make a habit of this..I understand the second half may be subjective so disregard if too obtuse.

(function ()
{
   FuncName1 = function (var1, var2, var3)
   {
       ....code n stuff....
   }

   FuncName2 = function (var1, var2)
   {
    .....code n stuff...
   }
 })();

Excellent explanations everyone. Thank You. So my follow on question would be then shouldn't every function be wrapped? For example the author wrapped two functions in one "scope or module". Couldn't those leak into each other?


So cookie monster to make the authors code even better I would do as such:

(function ()
{
   var FuncName1 = function (var1, var2, var3)
   {
       ....code n stuff....
   }

   var FuncName2 = function (var1, var2)
   {
    .....code n stuff...
   }
 })();

The key as you say in your comments is by using the keyword var keeps them in scope of the containing anonymous function. Not using var results in an implicit global scope.

Upvotes: 3

Views: 154

Answers (4)

Jian Huang
Jian Huang

Reputation: 1185

This pattern is called 'Module' in Javascript, used for information hiding.

According to the book 'Javascript: The good part'. The correct way of calling should be:

(function() {
    ...
}());

Not:

(function() {
    ...
})();

Another method:

!function() {
...
}();

Upvotes: 3

Sten Muchow
Sten Muchow

Reputation: 6711

Like the guys said above it creates modular code. If you set the anonymous function to return "things" and you set that to a variable you now have a closure that has name spaced goodness.

var name = (function() {

   var 
       lastName = 'Moody',
       firstName = Hank
   ;

   return {
      setName: function(newFirstName, newLastName) { 
                   firstName = newFirstName;
                   lastName = newLastName;
                },
      getName: function() { return firstName + " " + lastName; } 


    }

}());

Now you can get and set the code and it lives in it's own scope! Bam - Modular Design Pattern.

name.setName('Clark', 'Kent');
console.log(name.getName); // Will now output Clark Kent

Very powerful and simple design pattern.

Update:

Almost forgot the most important thing their name - IIFE or immediatetly invoked function expression!

Upvotes: 4

Thom Smith
Thom Smith

Reputation: 14086

The anonymous function creates a scope. Any definitions inside the anonymous function will not "leak" outside and pollute the global namespace. This lets you write more modular code. When you do need to export something from inside the block into the global namespace, you can do so explicitly.

Upvotes: 4

lyoung
lyoung

Reputation: 427

"Because variables and functions defined within a function may only be accessed inside, but not outside, that context, invoking a function provides a very easy way to create privacy."

http://benalman.com/news/2010/11/immediately-invoked-function-expression/

Upvotes: 3

Related Questions