Im having this closure Code :
for (var i = 0, link; i < 5; i++)
{
link = document.createElement("a");
link.onclick = aaa(i);
document.body.appendChild(link);
}
function aaa(num)
{
return function ()
{
alert(num);
};
} ;
Ive been reading a lot about closure lately.
There is ONE thing which I dont understand.
- When i==0 , it comes to aaa with i=0 and being executed which return new function which should lock the value
0.
its fine.( I understand this so far).
But what happens the i==1 ?
- It comes again to the SAME aaa and now it should lock the
1value. ok
But Wait ! it already saves the "closure" for the "0" value !
Does this structure(closure) is creating a new space in memory for each iteration ?
and if so - how can it be ? we have only one centralized aaa func !
link- you're creating multiple elements of which the create code is only apparent once in the source.