Thursday, April 8, 2010

Closure

Closure is one of the  most useful programming construct which I find very fasinating and exciting to use.
Closure: Innerfunction can access the enclosing function variables even after the enclosing has finished executing.

Simple example of closure:
(function EnclosingFunc()
{
     var x = {"Name": "Yashwant Patil"};
     this.PrintName = function()
     {
          alert(x.Name);
     } 
})();
this.PrintName();     //Output of this will be  Yashwant Patil

When PrintName is called, it is able to access the x variable even though the enclosing function has already exited. 
Closure are extensively used in lot of javascript libraries like JQuery , ASP.Net Ajax library etc.

Following examples will demonstrate where closures can be useful.

1) Closure can be used to maintain the state.
2) Closure can be used in callback functions.
3) Closure can be used to give a restricted scope to a variable, thus avoiding the global variable issue in javascript.
4) Closure are very useful in avoiding the "this" issue in javascript. Closure are extensively used in eventhandlers.

I think its a very powerful programming construct which can be little tricky to understand but once you get it, you will wonder how you ever lived without it. :)

-Yashwant

0 comments: