Call a function whose name is stored in a variable

This question already has an answer here:

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

  • To call function use

    Module[str]();
    

    As Module is an object, you can access the dynamic properties and methods of it by using the bracket notation.

    (function() {
      var Module = (function() {
        var fctToCall = function() {
          console.log('Foo');
        };
        return {
          fctToCall: fctToCall
        };
      })();
      var Module2 = (function() {
        var init = function() {
          var str = 'fctToCall';
          
          // Call as
          Module[str]();
        };
        return {
          init: init
        };
      })();
    
      Module2.init();
    })();

    Replace:

    var init = function () {
        var str = 'fctToCall';
        Module.str(); // here
    };
    

    With:

    var init = function () {
        var str = 'fctToCall';
        Module[str](); // here
    };
    

    Here, str is used as key to access the fctToCall function on Module .

    Then you can call Module2.init() , in your IIFE:

    (function() {
      var Module = (function() {
        var fctToCall = function() {
          document.write('Foo'); // (alert is broken in snippets)
        };
        return {
          fctToCall: fctToCall
        };
      })();
      var Module2 = (function() {
        var init = function() {
          var str = 'fctToCall';
          Module[str](); // Access & call `fctToCall`.
        };
        return {
          init: init
        };
      })();
      Module2.init(); // Call `init`.
    })();

    由于JS中的所有东西都是对象,所以可以使用对象表示法。

    Module[str]();
    
    链接地址: http://www.djcxy.com/p/94826.html

    上一篇: jquery:使用字符串作为函数(错误:字符串不是一个函数)

    下一篇: 调用名称存储在变量中的函数