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.
3 Answers 3
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
undefinedto itself
You should:
- Not use globals
Such:
var funcVar;
funcVar = function (a, b) {
var c = a + b;
alert (c);
};
funVar(1,2);
answered Dec 25, 2014 at 14:22
Quentin
949k137 gold badges1.3k silver badges1.4k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
answered Dec 25, 2014 at 14:24
Jörg W Mittag
371k79 gold badges457 silver badges666 bronze badges
Comments
This works. Thank you all.
var funcVar;
funcVar = 'function stop() {alert ("Test");}';
eval(funcVar);
stop();
1 Comment
Alex K.
If you are happy with all the potential problems of
eval you may prefer the new Function(body_string) syntaxlang-js
eval, but... what's the actual usecase? In other words, why do you think you want to do this?evalis your friend, it works for all things, just doeval(funcVar)and you're golden.evalis not your friend.evalis 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.evalis your friend that drinks all your beer and vomits on your couch. With friends like those...