JavaScript等同于PHP的call_user_func()

javascript equivalent of PHP's call_user_func()

谁知道有没有?

我想使用变量名来调用函数。

编辑:

我在这里张贴了我想做的事情:

http://jsfiddle.net/sAzPA/

1
  ...

js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
(function($){
  $.fn.MyPlugin = function(){

    return this.each(function(){
       var somefunction = function(arg1, arg2){ alert(arg1); },
           someotherfunction = function(arg1, arg2){ alert(arg2); },
           reallyimportantfunction = function(arg1, arg2){
            var foo = $(this).attr('id') + 'function';

            // here I want to call the function with the foo value as name, and pass it arg1 and arg2

            $()[foo](arg1, arg2); // <- doesn't work

           };

       reallyimportantfunction();
    });
  };  
})(jQuery);


jQuery(function($){
  $('#some').MyPlugin ();

});

如果在全局级别定义了一个函数,则该函数自动成为window对象的子级。

因此,您总是可以在通常只呼叫functionName();的任何地方呼叫window.functionName();

此外,由于在Javascript中,对象的工作方式类似于关联数组,因此您可以使用以下数组语法调用任何对象的任何子级:object['childName']。这包括函数,因此您可以对属于对象成员的任何函数执行object['functionName']();

将这两点结合在一起,您可以像下面这样调用任何全局定义的函数:

1
window['functionName']();

而且由于上例中的functionName是字符串,因此可以在括号中使用变量,这意味着您具有与PHP的call_user_func()相同的功能。

[编辑]

正如我所说,这适用于任何对象。 OP的注释表明,他要使用这种功能的功能在JQuery插件中。因此,它们很可能是JQuery对象的一部分,通常按如下方式调用:JQuery().functionName();(或用$代替JQuery)。

Javascript语法允许我们在可以使用.functionName()的任何地方使用['functionName'](),因此,以上述JQuery示例为例,我们可以将其更改为如下所示:

1
JQuery()['functionName']();`

但是该技术可以适用于任何Javascript对象。使用.functionName()的任何地方都可以用['functionName']()替换。


有很多方法可以实现这一目标。最快和最肮脏的方法(也是不安全的!)(以下示例中的PS:fnName是存储为字符串的函数的名称)

1
eval(fnName)

但是你也可以

1
            this[fnName]();//careful with"this" though. Try replacing with"window" if it doesnt work for you

或通过传递参数来调用它

1
this[fnName].apply(contextObject,argumentArray) //contextObject will be objest which will be referenced by the keyword"this" within the function body (fnName's body), argumentArrayy is the array of arguments you want to pass to function.


1
2
3
4
var a = function(foo) {console.log(foo);}

a.call(null, 'test');
a('test');