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
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).
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.
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.
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.
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 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]()
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With