What is JavaScript Closures??

What is JavaScript Closures??


JavaScript closures is nothing but they are stateful functions . So closure is a function inside function. They help to create isolated stateless functions
 Let us understand this with example:

<script>
function Counter()
{
var counter=0;
counter++;
alert(counter)
}
counter();  // first time
counter();   // second time
</script>

Note : This above counter has different state. When function or method runs it creates running memory. so counter variables create stack memory.
So when you call counter function call first time it is new running memory allocated and when you call counter function second time then second time new running memory allocated.

So we want that the function and variable should stay in memory.
So closure helps to object oriented programming concepts in JavaScript in very need to way.
So let's achieve this for example. We are familiar of object oriented programming this with example 

//Abstraction: show what is necessary
//Encapsulation: Hide complexity
//Inheritance:Parent child
//Ploymorphism: Depending on situation diff behavior
<script>
    function Employee(){
            var _employeename=""
                var _employeecode="";
                var _salary=function()
                        {
                      _dbconnect();
                            }
                var _Dbconnect=function()
                {
                }
        

    //abstraction
    return { 

        Employeename:_employeename,
        Employeecode:_employeecode,
         Salary:_salary
            }
   }
</script>

Note Explain the above code. Let's see .

These are private member in above function.

var _employeename=""
var _employeecode="";
var _salary=function()
{
_dbconnect();
}
var _Dbconnect=function()
{

}
}

and public member are:
return { 
Employeename:_employeename
Employeecode:_employeecode
Salary:_salary
}
So it is self content function so it is not using global variable. Now Let's call this function: 

var emp=new Employee()
emp.employeecode='8634'
emp.validate();

Employee.prototype=new contractemployee()
var cust=new contractemployee()
cust=new employee().

So closure is a function inside function. They help to create isolated stateless functions





















Post a Comment

0 Comments