Call a JavaScript function name using a string?

Property accessors can be used to access any object's properties or functions.

If the function is in the global scope, you can get it using the window object:

var myFunc = window[myFuncName];

This also works within the this scope:

var myFunc = this[myFuncName];

... or this[myFuncName];


I have worked on this problem, as I needed a function like this. Here is my sandbox code, not thoroughly tested, but can be a startpoint for others. Note that there is one eval() in the code as I couldn't figure out how to bypass that step, maybe a javascript quirk and cannot be done in any other way. Let me know if there is a way to get rid of eval() here!

executeFunctionByName = function(functionName)
{
    var args = Array.prototype.slice.call(arguments).splice(1);
    //debug
    console.log('args:', args);

    var namespaces = functionName.split(".");
    //debug
    console.log('namespaces:', namespaces);

    var func = namespaces.pop();
    //debug
    console.log('func:', func);

    ns = namespaces.join('.');
    //debug
    console.log('namespace:', ns);

    if(ns == '')
    {
        ns = 'window';
    }

    ns = eval(ns);
    //debug
    console.log('evaled namespace:', ns);

    return ns[func].apply(ns, args);
}


core = {
    paragraph: {
        titlebar: {
            user: "ddd",
            getUser: function(name)
            {
                this.user = name;
                return this.user;
            }
        }
    }
}

var testf = function()
{
    alert('dkdkdkd');
}

var x = executeFunctionByName('core.paragraph.titlebar.getUser', 'Ikon');
executeFunctionByName('testf');

Perhaps?

setTimeout ( "myFunc()", 1 );

Tags:

Javascript