Call jQuery defined function via string (JavaScript functions)

It’s possible to call functions via string. I can show you different ways to do it:

  1. Register the relevant function names on an object and then look up the function name on that object:
    jQuery(document).ready( function($) {
    
        function test1() {
            alert('test1');
        }
    
        function test2() {
            alert('test2');
        }
    
        // register functions on an object
        var funcList = {};
        funcList["test1"] = test1;
        funcList["test2"] = test2;
    
        var test_call = '2';
    
        var fn = 'test' + test_call;
    
        if (fn in funcList) {
            funcList[fn]();
        }
    
    });
  2. If they were global functions, they would be implicitly registered on the window object, but these are not global as they are scoped inside the document.ready handler function:
    jQuery(document).ready( function($) {
    
        var funcList = {};
    
        funcList.test1 = function test1() {
            alert('test1');
        }
    
        funcList.test2 = function test2() {
            alert('test2');
        }
    
        var test_call = '2';
        var fn = 'test' + test_call;
    
        if (fn in funcList) {
            funcList[fn]();
        }
    
    });
  3. Or, you could move the functions to the global scope so they are automatically registered with the window object like this:
    function test1() {
        alert('test1');
    }
    
    function test2() {
        alert('test2');
    }
    
    jQuery(document).ready( function($) {
    
        var test_call = '2';
        var fn = 'test' + test_call;
    
        if (fn in window) {
            window[fn]();
        }
    
    });
    

Reference link: http://stackoverflow.com/questions/7424476/call-jquery-defined-function-via-string