How to call a function whose name is defined in a string?

This question already has an answer here:

  • How to execute a JavaScript function when I have its name as a string 29 answers

  • if A is defined globally, then window["A"]() . However, there's no need to do that in javascript. Just pass the function itself rather than its name:

    function foo() {...}
    
    // BAD
    function callFunc(someName) { window[someName]() }
    callFunc("foo")
    
    // GOOD
    function callFunc(someFunc) { someFunc() }
    callFunc(foo)
    

    Like this:

    window[varName]()
    

    assuming it is in global scope

    If you have

    function A() {}
    function B() {}
    

    then you can do

    function C(parm) {
      parm();
    }
    

    if you call it with C(A) or C(B)

    DEMO


    You could assign the functions to properties of an object. Then in your executing function reference the property by name given the parameter passed to the function.

    var myFuncs = {
       a: function(){
         alert("Hello");
       },
       b: function(){
         alert("Goodbye");
       }
    };
    
    function execute(name){
       myFuncs[name]();
    }
    
    execute("a");
    execute("b");
    

    Working Example http://jsfiddle.net/ud6BS/

    链接地址: http://www.djcxy.com/p/94834.html

    上一篇: 在Javascript中执行一个动态命名的函数

    下一篇: 如何调用名称在字符串中定义的函数?