代码之家  ›  专栏  ›  技术社区  ›  Martin AJ

如何使用变量名执行函数?

  •  0
  • Martin AJ  · 技术社区  · 7 年前

    这是我的代码:

    $(function(){
      function myfunc(){
        alert("executed");
      }
      
      var function_name = "myfunc";
      window[function_name]();
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    如您所见,该函数没有定义。为什么?我怎样才能让它工作?

    3 回复  |  直到 7 年前
        1
  •  4
  •   Timovski    7 年前

    $(function(){
      window.myfunc = function(){
        alert("executed");
      };
    
      var function_name = "myfunc";
      window[function_name]();
    })
    
        2
  •  1
  •   Nina Scholz    7 年前

    window

    function myfunc(){
        alert("executed");
    }
    
    $(function(){
        var function_name = "myfunc";
        window[function_name]();
        window.foo = _ => console.log('foo');
        window.foo();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        3
  •  0
  •   Scott Marcus    7 年前

    window

    // Immediately-Invoked Function Expression (IIFE)
    // that keeps all of its contents out of the Global scope
    (function(){
    
      let functionHolder = {
        someFunction : function(){ console.log("You did it!"); }
      };
    
      // Set up a variable that has the same name as the function
      let funcName = "someFunction";
    
      // Call the function via the object
      functionHolder[funcName]();
    
    })()