开发者

JS Pass parameters as variables to an anonymous function and invoke it later -> parameter value problem

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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜