Skip navigation

Definition for closure : A closure is the local variables for a function – kept alive after the function has returned.

A nice example to explain closure.

//
// define a function which preserves data (count)
//
var CreateCounter = function(){
   var count, f;
   count = 0;
   f = function(){
      count = count+1;
      return count;
   }
   return f;
}

// create objects which remembers its own counter
var counter1 = CreateCounter();
var counter2 = CreateCounter();
alert(counter1());  // 1
alert(counter1());  // 2
alert(counter1());  // 3

alert(counter2());  // 1
alert(counter2());  // 2
alert(counter2());  // 3

alert(counter1());  // 4
alert(counter1());  // 5
alert(counter2());  // 4

Nice article about closure found at http://www.jibbering.com/faq/faq_notes/closures.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: