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

匿名 (未验证) 提交于 2019-12-03 07:50:05

问题:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!