JS Pass parameters as variables to an anonymous fu

2020-07-24 03:57发布

问题:

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.

回答1:

You have to create a new scope, where the current value of k is captured. JavaScript has only function scope, so you can do this with an immediate function:

var f = (function(value) {
    return function(){myFunction(value);};
}(k));

You could make this more readable by creating a named function which generates your anonymous function:

function getFunction(value) {
   return function(){myFunction(value);};
}

// later

var f = getFunction(k);