I have a problem calling an anonymous function with parameters passed as variables. If I save an anonymous function into an array after passing it a variable as parameter, then I change the variable and invoke the function, it prints the last value of the variable, not the value of the variable at the moment I pushed the anonymous function into my array. I simplify my code in the following example:
var arr = [];
function myFunction(index) {
alert(index);
}
function doPush() {
var k = 'hello';
var f = function(){myFunction(k);};
arr.push(f);
k = 'goodbye';
}
function invoker(op) {
op();
}
function invokePushed() {
invoker(arr[0]);
}
doPush();
invokePushed();
Well, invokePushed(); alert 'goodbye' instead of 'hello'.. My goal is to store into the array several functions and call them sequentially, but in this way all functions in my array have the same (the last) value of the parameters.
I know that I can solve this by pushing a string rappresentation of the function into the array:
var f = 'myFunction(\''+k+'\');';
and invoking it with eval in the invoker function, but my hope is to use the first method.
Is it possible?
Thanks,
Alessandro.