Wednesday, 15 October 2014

JavaScript Closure Simple Explanation

Hi,

Most of people around here having little confusion in understanding the concept of JavaScript Closures. They get bemused by typical definition/explanation given on various online resources. So, Here I'll try to explain Closures in simple terms.


A Closure is nothing more than a function that has a reference to a private variable. Private variables can be made possible with closures. 

For Eg. We've a function called myFunction()

function myFunction(myParam) //Constructor function

{

   this.myProp = myParam; 

}  



var myObj = new  myFunction("My Parameter"); //'myObj' is an object with type 'myFunction'



console.log(myObj.myProp); //Works correctly, Prints 'My Parameter'

Now, We make little modification to Constructor 'myFunction' like below

function myFunction(myParam) //Constructor function

{

   var myProp = myParam; // Changed from 'this.myProp' to 'var myProp'. It's a private variable & 'myProp' now exists only in the scope of 'myFunction' function  

}  



var myObj = new  myFunction("My Parameter"); //'myObj' is an object with type 'myFunction'



console.log(myObj.myProp); //It won't print 'My Parameter' but 'undefined' because 'myProp' is out of scope

Here comes Closure, So we can access 'var myProp' with the help of closure method like below.

function myFunction(myParam) //Constructor function

{

   var myProp = myParam; // It's a private variable & 'myProp' now exists only in the scope of 'myFunction' function  
   this.getMyProp = function(){ //It's a Closure which has a reference to the private varaiable 'var myProp'
          return myProp;
    };
 }  



var myObj = new  myFunction("My Parameter"); //'myObj' is an object with type 'myFunction'



console.log(myObj.getMyProp()); //Works correctly, Prints 'My Parameter'. This is achieved with the help of Closure.
That's it. This is called a JavaScript closure. It makes possible for a function to have Private variables. A closure is a function having access to the parent scope, even after the parent function has closed. So Private variables can be made possible with the help of closures. Hope You understood. Cheers..:)

No comments:

Post a Comment

blogger visitor