Link to home
Start Free TrialLog in
Avatar of milani_lucie
milani_lucieFlag for United States of America

asked on

Closure in JavaScript

Hi,

I have written the code in JavaScript two ways (WAY-1.html, WAY-2.html). Find the attachments. The second way (WAY-2.html) works fine as expected. Can you please do let me know why ? BTW: What is this "Closure" thing ? Also please explain a little bit !

Thanks
WAY-1.html
WAY-2.html
Avatar of nap0leon
nap0leon

In "Way1", because your function looped through everything when the page loaded, the value of "i" is 5, so you alert('5') every time you click.

In "Way2", you created a function call on each item.  This function call passes the value that "i" was at the time of the function creation.  In this way, your page is able to alert('1'), alert('2'), etc.
Avatar of milani_lucie

ASKER

I am still NOT clear ... Can you please explain me in simple terms ?

WAY - 1

elements(i).onclick = function() { alert(i); };

means

if i = 0 then alert(0)
if i = 1 then alert(1)
if i = 2 then alert(2)
if i = 3 then alert(3)
if i = 4 then alert(4)

Am i correct ?

Thanks
Avatar of HonorGod
Sorry ... I cannot go through the entire story with deep URLs. Please provide me point-to-point explanation so that i can understand it better !! Even i have provided you the code also.

Thanks
ASKER CERTIFIED SOLUTION
Avatar of nap0leon
nap0leon

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial