Search code examples
javascriptfunctionwindow

Javascript calling functions in array by window[string]


function foobar(){
    alert("Hello World");
}


var funcName = "foobar";
var func = window[funcName];
if (typeof func === "function" ) func();

Hello! I would like to call function like above

var functions = {
    function1 : function(){ return },
    function2 : function(){ return },
    function3 : function(){ return },
    function4 : function(){ return }
}

with the object of functions.

I've tried

window["functions.function1"] // or
window["functions['function1']"]

and they don't work! How can I achieve this? Thank you!

edited: "with the array of functions." to "with the object of functions."


Solution

  • Sticking with your concept of using strings, it would be:

    window["functions"]["function1"]();
    

    If you want a single string for it, you can use split and walk through the parts:

    var name = "functions.function1";
    callFunction(name);
    
    function callFunction(name) {
        var parts = name.split(".");
        var n;
        var obj = window;
        for (n = 0; n < parts.length; ++n) {
             obj = obj[parts[n]];
             if (!obj) {
                 return;
             }
        }
        return obj ? obj() : undefined;
    }
    

    Side note: All properties of window are a globals. The global namespace is incredibly crowded, so adding more globals is a Bad Idea(tm). Instead, wrap your code in a scoping function and use your own object rather than window.