Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function name as a string in self executing function

Tags:

javascript

I am running a self executing function in javascript to not interfere with any global variables on a page. I have a string with the name of a function I want to call. The function is declared inside my self-executing function. Is there a way to call that function by using the string?

(function(document, window){
    var functionName = "myFunction";

    window[functionName](); //This does not work...        

    function myFunction(){
        //Do some stuff
    }

}(document, window)

I found this: How to execute a JavaScript function when I have its name as a string

but my function is self executing without a name, so I have no way to reference it with the window variable.

like image 530
Clint Avatar asked May 01 '26 06:05

Clint


1 Answers

This is just a cleaner version of what others have suggested, no global pollution, no eval, and no obscure variable references (arguments.callee and "this").

// Not sure why you were passing in doc and window, so I took it out for clarity
(function(){
    var funcs = {
      funcA: function () { return "a"},
      funcB: function () { return "b"}
    };

    var functionName = "funcA";
    funcs[functionName]();  
}();

This approach does require you to declare the functions before you use them.

like image 134
Juan Mendes Avatar answered May 02 '26 19:05

Juan Mendes