Rodrigo Calix
Rodrigo Calix

Reputation: 637

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.

Upvotes: 2

Views: 213

Answers (1)

Roy Miloh
Roy Miloh

Reputation: 3411

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);

Upvotes: 2

Related Questions