milani_lucie
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
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
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
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
Check this question, and the provided answers:
https://www.experts-exchange.com/questions/23093328/What-are-closure-and-enclosure.html
https://www.experts-exchange.com/questions/23093328/What-are-closure-and-enclosure.html
ASKER
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
Thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.