Using a string as a function name

E

Euperia

Hi

I would like to use a string from an array to call a function. For
example, I have a list of functions called A.B,C,D etc and for various
situations I need to call a a different range of functions:

var myFunctions = ["A","C","G","B","E"];

for (i = 0; i < myFunctions.length; i++) {
errorcode = myFunctions(); // I want to call A(); B() etc
}


Is it possible with Javascript, and if so, how?

Regards
Andrew
 
S

Steve van Dongen

Hi

I would like to use a string from an array to call a function. For
example, I have a list of functions called A.B,C,D etc and for various
situations I need to call a a different range of functions:

var myFunctions = ["A","C","G","B","E"];

Change this line to
var myFunctions = [A,C,G,B,E];
so that you have an array of function references instead of an array
of strings.
for (i = 0; i < myFunctions.length; i++) {
errorcode = myFunctions(); // I want to call A(); B() etc
}


Is it possible with Javascript, and if so, how?


Regards,
Steve
 
D

Douglas Crockford

I would like to use a string from an array to call a function. For
example, I have a list of functions called A.B,C,D etc and for various
situations I need to call a a different range of functions:

var myFunctions = ["A","C","G","B","E"];

for (i = 0; i < myFunctions.length; i++) {
errorcode = myFunctions(); // I want to call A(); B() etc
}


Functions are values. You can use myFunctions to store the functions themselves,
not just their names.

var myFunctions = [A, C, G, B, E];

This assumes that function A et al have been defined.

You could go a step further and define the functions in the array literal.

var myFunctions = [function A() {
...
}, function C() {
...
}, function G() {
...
}, function B() {
...
}, function E() {
...
}];

http://www.crockford.com/
 
V

Vjekoslav Begovic

Euperia said:
Hi

I would like to use a string from an array to call a function. For
example, I have a list of functions called A.B,C,D etc and for various
situations I need to call a a different range of functions:

var myFunctions = ["A","C","G","B","E"];

for (i = 0; i < myFunctions.length; i++) {
errorcode = myFunctions(); // I want to call A(); B() etc


for (i = 0; i < myFunctions.length; i++) {
errorcode = window[myFunctions]();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,079
Messages
2,570,574
Members
47,206
Latest member
Zenden

Latest Threads

Top