Most of the Java script Developer stuck in closure even they use closure in multiple places. There are many blogs to explain Closure. I came across most of the blogs and decided to make it more simple as I can.
In a very simple way I can say Closure is a function which has the memory of Variables in which it was defined.
Ex.1:
function increment(i){
return function(){
return i++;
}
}
var increase_1 = increment(5); //passing a reference or scope variable 5
//increase_1 store value of i as 5 in memory
increase_1() //5
increase_1() //6
increase_1()
//7
Let's have another simple example
Ex.2:
add(3,5);
add(3)(5);
Now I need a function that can execute both expression....
function add(a,b){
if(arguments.length===2){
return a+b;
} else {
return function(b){
return a+b;
}
}
}
Ex:3:
// A typical example
function addLinks () {
for (var i=0, link; i<5; i++) {
link = document.createElement("a");
link.innerHTML = "Link " + i;
link.onclick = function(){
console.log(i);
}
document.body.appendChild(link);
};
}
addLinks();
//What will be the output of this.
When you execute this it create a link, and on click it will print some value.
So what would be the value it print on click of link1. Think about it for a while..... I know, initially you get confused.
yes it prints 5.
Not only click on this particular link but on each link, it gives you 5.
So, now I want to print 0,1,2,3,4. Yes that's right when I click on link0, it prints 0, on link1, it prints 1 and so on..
Now, I want to you check the example 1 closely and try to implement in the same way and try to memorise some thing self executing annonmys function.
function addLinks () {
for (var i=0, link; i<5; i++) {
link = document.createElement("a");
link.innerHTML = "Link " + i;
link.onclick = function(c){
return function(){
console.log(c);
}
}(i);//passing a reference
document.body.appendChild(link);
};
}
addLinks();
So, if you see this example closely, when an event handler is being bind with the link, a reference or scope is passed.
This is the same way, in which jQuery was implemented.