JS将参数作为变量传递给匿名函数并稍后调用它 - >参数值问题 [英] JS Pass parameters as variables to an anonymous function and invoke it later -> parameter value problem

查看:129
本文介绍了JS将参数作为变量传递给匿名函数并稍后调用它 - >参数值问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题调用一个匿名函数的参数作为变量传递。如果我在将一个匿名函数传递给一个变量作为参数之后将其保存到数组中,那么我改变这个变量并调用该函数,它打印变量的最后一个值,而不是我推送匿名函数时变量的值到我的数组。
我在下面的例子中简化我的代码:

  var arr = [] 

function myFunction(index){
alert(index);
}

function doPush(){
var k ='hello';

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

arr.push(f);

k ='goodbye';
}

函数invoker(op){
op();
}

函数invokePushed(){
invoker(arr [0]);
}

doPush();
invokePushed();

好吧,invokePushed alert'goodbye'而不是'hello'..我的目标是存储到数组中的几个函数,并按顺序调用它们,但这样我的数组中的所有函数都有相同的(最后一个)参数的值。



我知道我可以通过将函数的字符串rappresents推入数组来解决这个问题:

  var f ='myFunction(\''+ k +'\');'; 

并在调用器函数中使用eval调用它,但我希望使用第一个方法。 / p>

有可能吗?



感谢,



Alessandro。

解决方案

您必须创建一个新作用域,其中 k 。 JavaScript只有函数范围,因此可以使用立即函数来实现:

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

您可以通过创建一个命名函数来生成您的匿名函数,从而提高可读性:

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

//以后

var f = getFunction(k);


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

这篇关于JS将参数作为变量传递给匿名函数并稍后调用它 - >参数值问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆