I need to "parse"/create JS function from string. Lets say:
var str = "function(data,type,full,meta){ return'works';}";
I tried to use javascript eval(str) function but I always get this error from console when trying this
eval(str)
Uncaught SyntaxError: Unexpected token (
VM:2323:1
I don't see anyting wrong with the syntax.
That's because there is nothing which forces it to be parsed as a function expression, so it's parsed as a function declaration.
And function declarations require a name. From Function Definition ,
FunctionDeclaration : function Identifier ( FormalParameterList opt ) { FunctionBody } FunctionExpression : function Identifier opt ( FormalParameterList opt ) { FunctionBody }
An easy fix (if you are sure the string has a proper syntax) would be wrapping it in parentheses. Then it will be parsed as a function expression.
eval('(' + str + ')')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.