tags:

views:

72

answers:

3

Hi,

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

+10  A: 

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.

David Dorward
Nice idea, thank you very much!
Peter
I'm more curious as to why someone would be creating 100 functions that differ by only an index...
colithium
A: 

You can also try

function at_26(){};
function at_21(){};
function at_99(){};

var test_id = 21;   
eval('at_'+test_id+'()'); 

But use this code if you have very strong reasons for using eval. Using eval in javascript is not a good practice due to its disadvantages such as "using it improperly can open your script to injection attacks."

Yogesh
No! Do not use `eval()` in this case! There are much better solutions here!
elusive
@elusive : Thats correct, better solutions always be used. I have just given alternative solution. Hope you don't mind it.
Yogesh
@Yogesh: Since not everyone necessarily knows the evilness of `eval()`, you should provide this information in your post. Nobody should use this solution unless he has a very good reason and is exactly knowing what he is doing. `eval()` has its valid uses but this is not one of them.
elusive
@elusive: Thanks for advice. I have added disclaimer now. Please check.
Yogesh
A: 

You were close.

var test_id = 21
this['at_'+test_id]()

However, what you may want:

at = []
at[21] = function(){ xxx for 21 xxx }
at[test_id]()
JeanHuguesRobert