r/learnprogramming•
[deleted]

Javascript closures question

I'm new to Javascript. Is there a way to capture a variable in a closure by VALUE instead of by REFERENCE? For example, I want this code to alert 0, 1, 2. It alerts 3,3,3 however.

var test = [ ];
for(var i = 0; i < 3; ++i) {
	test[i] = function() { return i; }
}
for(var k = 0; k < 3; ++k) {
	alert(test[k]());
}

Posted Nov 4, 2010, 2:16 AM UTC

21
Loading comments…