1

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!!

3 Answers 3

6

I made it a bit fancier to show you how you can use it.

var thecall = function(name){alert("hi " + name + ", this works");};

function myFunction(function_ref)
{
  function_ref('Mark');
}

myFunction(thecall);
Sign up to request clarification or add additional context in comments.

Comments

1

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:

var thecall = function() {
   alert("hi, this works");
};

function myfunction(someFunc)  {
   someFunc();    // call the function that was passed
}

myfunction(thecall);   // pass reference to thecall

Note that when passing the reference to the thecall function there are no parentheses, i.e., you say thecall not thecall(): if you said myfunction(thecall()) that would immediately call thecall and pass whatever it returned to myfunction. Without the parentheses it passes a reference to thecall that can then be executed from within myfunction.

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:

var menuItems = [];
function addMenuItem(menuText, menuFunction) {
   menuItems.push({ "menuText" : menuText, "menuFunction" : menuFunction });
}

function test1() {
   // do something
}

addMenuItem("Test 1", test1);
addMenuItem("Test 2", function() { alert("Menu 2"); });

// and to actually call the function associated with a menu item:
menuItems[1].menuFunction();

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.)

Comments

0

I think your looking for the eval function.

var code= 'alert("hi, this works");';
eval(code);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.