I am a C # developer and used to work in C #. I currently have to work with anonymous javascript functions and experience a problem with the following snippet:
function ClosureTest() { var funcArray = new Array(); var i = 0; while (i < 2) { var contextCopy = i; funcArray[i] = function() { alert(contextCopy); return false; }; i++; } funcArray[0](); funcArray[1](); }
I expect the first call to funcArray() say 0 , and the second to 1 . However, both of them say 1 . How is this possible?
We write var contextCopy = i to make sure that I create a copy of i -variable. Then in each while iteration, I create a completely new function pointer. Each function refers to its own copy of i , which is contextCopy . However, both created functions for one reason or another refer to the same contextCopy -variable.
How does it work in javascript?
source share