Actual understanding : Closure is a function that stays alive or connected to its parent Scope or parent function even after Parent scope or parent functions execution is over.
Problem : Suppose you are told to write a function that increments counter value by 1, What will you do ?
Obviously We would Code
var counter = 0;
function add() {
return counter += 1;
}
add(); //Outputs 1
add(); //Outputs 2
add(); //Outputs 3
But this code is considered buggy as counter variable is directly accessible and any one can set value directly without using add() function
So To make above code bulletproof we add closure function to it
Solution 1 :
var add = (function () { //outer function var counter = 0; return function () {return counter += 1;} //inner or closure function })();
add(); //Outputs 1 add(); //Outputs 2 add(); //Outputs 3
Explanation : In above code its Self firing function that executes outer function once and returns anonymous closure inner function that does not executes at first time but maintains connection
with outer function.
Solution 2 :
var add = function(){ //Outer Function
var counter = 0;
return function(){ //Inner or closure Function
counter += 1;
console.log(counter)
}
}
var yo = add()
yo() //output 1
yo() //output 2
yo() //output 3
No comments :
Post a Comment