Search code examples
javascriptjquerystringfunctioncall

Javascript - How to call any function with a string?


I want to know how to call a function with a string value

In some other questions i found this: window["functionName"](arguments);, and i assume is not working cause my functions are not global, and i don't want them to be global.

I have an example here:

(function ( $ ) {
    "use strict";
    var testing,
    showMe;

    testing = function(){
        alert('Working');
    };

    showMe = function(test){
        window[test](arguments);
    }

    $(document).ready(function(){
        showMe('testing');
    });
})(jQuery);

As you can see, what i want is call the function, testing() using just a String value.


Solution

  • window is an object. You can place it inside an arbitrary object:

    (function ( $ ) {
        "use strict";
        var testing,
        showMe,
        funcs = {};
    
        funcs.testing = function(){
            alert('Working');
        };
    
        showMe = function(test){
            funcs[test](arguments);
        }
    
        $(document).ready(function(){
            showMe('testing');
        });
    })(jQuery);