Possible Duplicate:
How to execute a JavaScript function when I have its name as a string
Struggling with this one, and I can’t seem to find a good resource on it.
Background: I’m creating a step system, and I’m passing the direcition/order within an attribute data-step="1". This controls the ID that will be shown (that parts easy), but also the function that needs to be called in order to grab the correct information.
The question is basically, how can I call a function who’s name I need to build dynamically?
IE:
step1(); step2(); Except I want to dynamically ADD that number in there.
// In an essense, what I'm trying to achieve:
// It's always called step and then followed by a number
[step + directionNumber](); // which isn't working
Also trying to avoid using eval since we all know it’s evil 🙂
Use
When you write in the global scope
you’re defining a property of the global object (
window) with namesomeNameand value the function.It’s equivalent to
So you can call your function as
window.someName();or, more useful here, aswindow['someName']();A better solution would probably be to define an array of functions :
then you can call them using
stepFunctions[directionNumber]();