Javascript - Variable in function name, possible?
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
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]()
An example to pass an array of params to those composed functions, .
/* Store function names and match params */
let at = {
at_26 : (a,b,c) => at_26(a,b,c),
at_21 : (a,b,c) => at_21(a,b,c),
at_99 : (a,b,c) => at_99(a,b,c),
at_om : (a,b,c,d,e) => at_om(a,b,c,d,e)
}
/* Dynamic function router: name + array of Params */
function dynFunc(name, arrayParams){
return at[name](...arrayParams)
}
/* Usage examples */
dynFunc(`at_${99}`, ["track001", 32, true])
dynFunc("at_" + "om", ["track007", [50, false], 7.123, false, "Bye"])
/* In the scope */
function at_99(a,b,c){
console.log("Hi! " + a,b,c)
console.log(typeof(a), typeof(b), typeof(c))
}
function at_om(a,b,c,d,e){
console.log("Hi! " + a,b,c,d,e)
console.log(typeof(a), typeof(b), typeof(c), typeof(d), typeof(e))
}
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."
There is a better way then the window object - which is NOT friendly in firefox - use "self" instead - so in the example posted by Quentin it looks like this:
self['at_' + test_id]();
精彩评论