Ok hopefully this come across correctly. I am building a universal javascript function that will build a menu and then also build the functions that each menu item would call. To do this, I need to pass a list of the commands to be called for each option.
So for example:
var thecall = 'alert("hi, this works");';
function myfunction(thecall)
{
//In here I want to excute whatever commands is listed in variable thecall
.....
}
I’m sure doing it this way is completely stupid, but I don’t know how else to do this.
Basically, I need my function to perform other functions on a variable basis.
Thanks!!
You can execute arbitrary strings of JavaScript using
eval(), but that is not the best solution for you here (it’s almost never the best solution).Functions in JavaScript are themselves objects which means you can store multiple references to the same function in multiple variables, or pass function references as parameters, etc. So:
Note that when passing the reference to the
thecallfunction there are no parentheses, i.e., you saythecallnotthecall(): if you saidmyfunction(thecall())that would immediately callthecalland pass whatever it returned tomyfunction. Without the parentheses it passes a reference tothecallthat can then be executed from withinmyfunction.In your case where you are talking about a list of menu items where each item should call a particular function you can do something like this:
Notice the second menu item I’m adding has an anonymous function defined right at the point where it is passed as a parameter to
addMenuItem().(Obviously this is an oversimplified example, but I hope you can see how it would work for your real requirement.)