2

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 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, that's exactly what I was looking for. I just changed getFunction in this way to make it generic: function getFunction(f, value) { return function(){f.apply(null, value);}; } Regards, Alessandro.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.