Following part of my javscript(using jquery).
list = [\'a\', \'b\', \'c\'];
for(var i = 0 ; i< list.length ; i++) {
$(\"click here\").
Create a closure to retain the value of i
for the particular iteration when the function is executed, without a closure i
remains in scope causing all of the created functions to eventually have the value at the last iteration:
var list = ['a', 'b', 'c'];
for(var i = 0 ; i< list.length ; i++) {
var func = createFoo(list[i]);
$("click here").
click(func).
appendTo('#sometag');
}
function createFoo(value){
return function(){
foo(value);
};
}
function foo(val) {
console.log(val);
}
JS Fiddle: http://jsfiddle.net/5dUgw/
Also note you need to change int
to var
since this is JS.