Hi I want to create several function which work similar but use a slightly different value. I cannot change the parameters because I use these for a callback of a library. My first idea:
for(i = 0; i < 3; i++) {
f = function() {
console.log(i);
};
}
This obviously copies a refence of i to the function but I rather want to value at that time so that each function outputs a different value. I appreciate your help.
1 Answer 1
you may try this way:
var f=[];
for(i = 0; i < 3; i++) {
f[i] = (function(index) {
return function() {
console.log("My value: " + index);
}
})(i);
}
working demo here
answered Jan 20, 2014 at 10:26
Mithlesh Kumar
7587 silver badges16 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Mithlesh Kumar
Have you check demo this will create 3 functions having different values (this idea come from "but use a slightly different value").
lang-js