0

Happy Holidays to all. I'm trying to execute a function that I have saved in a variable, as I could do this?

I tried this.

funcVar = 'function (a, b) {c = a + b; alert (c);}';

document.write (funcVar);

but has no functionality, I want to use that function that is in the variable at some point.

4
  • Write?! You could eval, but... what's the actual usecase? In other words, why do you think you want to do this? Commented Dec 25, 2014 at 14:22
  • eval is your friend, it works for all things, just do eval(funcVar) and you're golden. Commented Dec 25, 2014 at 14:23
  • 3
    eval is not your friend. eval is slow, hard to debug, and causes more problems than it solves. It solves almost no problems that can't be solved better with another technique. Commented Dec 25, 2014 at 14:23
  • 2
    eval is your friend that drinks all your beer and vomits on your couch. With friends like those... Commented Dec 25, 2014 at 14:24

3 Answers 3

2

You need to:

  • Write it as a function, not a string
  • Call it, not write it to the document as if it were a string of HTML
  • Pass arguments as it doesn't make sense to add undefined to itself

You should:

  • Not use globals

Such:

var funcVar;
funcVar = function (a, b) {
    var c = a + b; 
    alert (c);
};
funVar(1,2);
Sign up to request clarification or add additional context in comments.

Comments

0

That's not a function, that's a string. You need to remove the quotes. And you need to execute it, not print it:

var funcVar = function (a, b) {c = a + b; alert (c);};

funcVar(23, 42);

Comments

-1

This works. Thank you all.

var funcVar;
funcVar = 'function stop() {alert ("Test");}';
eval(funcVar);

stop();

1 Comment

If you are happy with all the potential problems of eval you may prefer the new Function(body_string) syntax

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.