JavaScript eval() “syntax error” on parsing a function string

前端 未结 2 355
不思量自难忘°
不思量自难忘° 2020-12-09 17:23

I have a bit of JavaScript code that is specified in a configuration file on the server-side. Since I can\'t specify a JavaScript function in the configuration language (Lu

相关标签:
2条回答
  • 2020-12-09 17:50

    The parentheses are required because they force the thing inside them to be evaluated in an expression context, where it must be a function-expression.

    Without the parentheses, it could instead be a function declaration, and it seems as if it is sometimes being parsed that way - this could be the source of the odd/inconsistent behaviour you're describing.

    Compare this function declaration:

    function foo(arg) {}
    

    with this function-expression:

    var funcExpr = function foo(arg) {};
    

    It also has to be a function-expression if it doesn't have a name. Function declarations require names.

    So this is not a valid declaration, because it's missing its name:

    function (arg) {}
    

    but this is a valid, anonymous function-expression:

    var funcExpr = function(arg) {};
    
    0 讨论(0)
  • 2020-12-09 18:02

    To do what you want, wrap your string in parentheses:

    a = "function(value) { return Math.abs(value);}";
    b = eval("("+a+")");
    b(-1);
    
    0 讨论(0)
提交回复
热议问题