Javascript - Variable in function name, possible?

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]()

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.


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."

Tags:

Javascript