Your functionString
contains exactly the string
"function (message) { console.log(message); }"
Assessing it as-is, there is a JavaScript engine with the wrong syntax (there is no name for this function). JavaScript expects a construct as function <name>(<params>) { }
. Alternatively, you can use an anonymous function (i.e. the Name is missing), but only as a parameter or in the context of evaluating the expression. The minimum typical expression for evaluating is (function() {})()
If you want a fantasy,! !function() {}
also good - the exclamation mark in front turns it into a logical expression that requires evaluating the function before denying the output.
So in your example, this will work:
eval("("+functionString+")('abc')");
because then you make an anonymous function call - something that JavaScript can live with.
Alternatively, you can also use only parentheses, then you need to assign the result to what you can use later:
var foo = eval("("+functionString+")"); foo('ddd');
Here's a little proof / playground to find out about this: http://jsfiddle.net/Exceeder/ydann6b3/
source share