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

前端 未结 2 354
不思量自难忘°
不思量自难忘° 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) {};
    

提交回复
热议问题