Using eval on a function string

前端 未结 3 1943
傲寒
傲寒 2021-01-26 04:23

I am doing :

eval(\'function(){ console.log(\"Hello World\"); }\')();

But that gives error :

Uncaught SyntaxError: Unexpected t         


        
3条回答
  •  日久生厌
    2021-01-26 04:57

    The eval operator expects a Program as input, and the grammar of JavaScript requires that all top-level program elements are either declarations or statements.

    The spec says:

    Let prog be the ECMAScript code that is the result of parsing x as a Program.

    function can't start a top-level statement, but it can start a function declaration, but only when it has a name.

    That's why you get "Unexpected token ("; it expects a function name before the parenthesis that opens the argument list.

    As others have noted, to eval a function, you need to trick the JavaScript parser into finding an expression where it expects a statement. Wrapping the body in parentheses is one way to do this.

提交回复
热议问题