Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...