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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With