Using eval on a function string

前端 未结 3 1939
傲寒
傲寒 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: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");
    

提交回复
热议问题