javascript equivalent of PHP's call_user_func()


javascript equivalent of PHP's call_user_func()

有人知道是否有吗?

我想用变量名调用一个函数。


编辑:

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

http://jsfiddle.net/sAzPA/

<div id="some">
  ...
</div>

js:

(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对象的子对象。

因此你总是可以在任何地方调用window.functionName();,而你通常只调用functionName();

进一步,因为在Javascript对象工作像关联数组,你可以调用任何对象的任何子使用数组语法像这样:object['childName']。这包括函数,所以你可以对任何作为对象成员的函数执行object['functionName']();

结合这两点,您可以调用任何全局定义的函数,如下所示:

window['functionName']();

由于上面示例中的functionName是一个字符串,您可以在括号中使用变量,这意味着您获得了与PHP的call_user_func()相同的功能。

[编辑]

如我所述,这适用于任何对象。OP的评论指出,他想以这种方式使用的函数是在JQuery插件中。因此,它们很可能是JQuery对象的一部分,通常会被这样调用:JQuery().functionName();(或者用$代替JQuery)。

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

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

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

有很多方法可以达到这个目的。最快和最脏(和不安全!)的方法是(PS:fnName在下面的例子中是作为字符串存储的函数名)

eval(fnName)

但是你也可以做

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

或通过传递参数

来调用它
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.
var a = function(foo) {console.log(foo);}
a.call(null, 'test');
a('test');