jquery:使用变量从变量调用函数

时间:2014-03-25 07:34:33

标签: javascript jquery

如何回调变量中定义的函数(我这样做了)... 不仅仅是如何将变量传递给该函数(也被定义为变量)

实施例: 函数变量,变量是变量....

function ffunction(Functionvariable,variable){
     Functionvariable(variable); //This is actually not working...how to do this...
}

我试过了,

function ffunction(Functionvariable,variable){
     eval(Functionvariable + '('+ variable + ')'); //no luck
}

这是有效的......

function ffunction(Functionvariable,variable){
         eval(Functionvariable)(variable);
    }

2 个答案:

答案 0 :(得分:2)

只要避免使用保留字,你的第一个解决方案就可以了 这是小提琴http://jsfiddle.net/6R3ye/

function dummy(func, v){
    eval(func)(v);
};
var f = 'alert';
var x = 'abc';
dummy(f, x);

答案 1 :(得分:0)

我收集了4种方法,你可以使用1种或更多种方法

fiddle

function ffunction(fn, p1, p2) {
  console.log("ffunction is calling \n" + fn.toString() + "\nwith " + p1.toString());

  eval(fn)(p1, p2);
  fn(p1, p2);
  fn.call(fn, p1, p2);
  fn.apply(fn, [p1, p2]);
}

function f1(p1, p2){
  console.log("f1 got " + p1.toString() + " and " + p2.toString());
}

ffunction(f1, 'foo', 'bar');
相关问题