Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to call a Javascript function using the value of a string variable? [duplicate]

I've seen this technique for calling a Javascript function based on the value of a string variable.

function foo() {
    alert('foo');
}

var test = 'foo';

window[test]();  //This calls foo()

Is this the accepted way to do it or is there a better way? Any cross-browser issues to worry about?

like image 687
Mark Biek Avatar asked Jul 17 '09 16:07

Mark Biek


Video Answer


2 Answers

Looks fine to me. I would probably create a simple helper function like following:

function runFunction(name, arguments)
{
    var fn = window[name];
    if(typeof fn !== 'function')
        return;

    fn.apply(window, arguments);
}

//If you have following function

function foo(msg)
{
    alert(msg);
}

//You can call it like

runFunction('foo', ['test']); //alerts test.
like image 196
SolutionYogi Avatar answered Oct 26 '22 21:10

SolutionYogi


I personally wouldn't bother even with a helper function

  window[someKey]('test')

would be fine.

However I wouldn't general maintain a set of possible functions to call at the global scope anyway. Hence I would use a more general pattern:-

 obj[someKey]('test')

where obj may be this, a property of this or variable from a closure.

like image 24
AnthonyWJones Avatar answered Oct 26 '22 19:10

AnthonyWJones