Using eval on a function string

前端 未结 3 1914
傲寒
傲寒 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:41

    eval expects a statement but:

    • function(){} is not valid as a statement because the function name is missing.

    • (function(){}) is instead recognized because the statement is a "statement expression".

    The problem is that function as first token triggers the function declaration rule when a statement is expected. When an expression is expected instead (e.g. inside parenthesis) then function triggers the function expression rules where a name is optional but not mandatory.

    0 讨论(0)
  • 2021-01-26 04:44

    What you want is this:

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

    Let's break it down. You have a self invoking function (a function that calls itself):

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

    And you're passing it as a string argument to the eval method:

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

    Your main error is trying to call what eval returns by adding parenthesis on the end of the eval method call. If you want the function your passing to immediately invoke itself, the added parenthesis should be part of the thing your passing to eval.

    I'm assuming you're trying to do something other than call "Hello World", as you could simply do this:

    eval( 'console.log("Hello World");' );
    

    Or, dare I say:

    console.log("Hello World");
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题