Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  75] [ 7]  / answers: 1 / hits: 31363  / 15 Years ago, fri, july 17, 2009, 12:00:00

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?


More From » function

 Answers
7

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.

[#99107] Monday, July 13, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alexandreah

Total Points: 720
Total Questions: 85
Total Answers: 90

Location: Central African Republic
Member since Fri, Jun 5, 2020
4 Years ago
alexandreah questions
Mon, Aug 9, 21, 00:00, 3 Years ago
Wed, Jan 8, 20, 00:00, 4 Years ago
Mon, Dec 16, 19, 00:00, 5 Years ago
Fri, Sep 27, 19, 00:00, 5 Years ago
;