Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Variable in function name, possible?

Tags:

javascript

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

like image 231
Peter Avatar asked Sep 17 '10 07:09

Peter


People also ask

Can variable name and function name be same JavaScript?

Variables and functions share the same namespace in JavaScript, so they override each other. if function name and variable name are same then JS Engine ignores the variable. With var a you create a new variable. The declaration is actually hoisted to the start of the current scope (before the function definition).

Can we use a function name as a variable name?

The best suggestion is to discontinue the use of function names as variable names completely. However, in certain applications in which this is not possible, place the relevant code in a separate script and then invoke the script from the function.

Can you declare a variable in a function JavaScript?

Variable means anything that can vary. In JavaScript, a variable stores the data value that can be changed later on. Use the reserved keyword var to declare a variable in JavaScript.

Can a variable be a name in JavaScript?

JavaScript IdentifiersIdentifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume). The general rules for constructing names for variables (unique identifiers) are: Names can contain letters, digits, underscores, and dollar signs. Names must begin with a letter.


3 Answers

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.

like image 154
Quentin Avatar answered Oct 24 '22 08:10

Quentin


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]()
like image 28
JeanHuguesRobert Avatar answered Oct 24 '22 07:10

JeanHuguesRobert


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

like image 1
Nik Avatar answered Oct 24 '22 07:10

Nik