Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
96
rated 0 times [  100] [ 4]  / answers: 1 / hits: 66202  / 14 Years ago, fri, september 17, 2010, 12:00:00

i hope this question is not too simple, but i have no idea :(



How can i start a function with a var in the function name?



For example ...



my functions



function at_26();
function at_21();
function at_99();


start the function



var test_id = 21;   
at_'+test_id+'(); // doesn't work


I hope somebody can help me.



Thanks in advance!
Peter


More From » javascript

 Answers
80

Store your functions in an object instead of making them top level.



var at = {
at_26: function() { },
at_21: function() { },
at_99: function() { }
};


Then you can access them like any other object:



at['at_' + test_id]();


You could also access them directly from the window object…



window['at_' + test_id]();


… and avoid having to store them in an object, but this means playing in the global scope which should be avoided.


[#95589] Wednesday, September 15, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
turnerf

Total Points: 620
Total Questions: 101
Total Answers: 109

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
turnerf questions
;