Using eval on a function string

前端 未结 3 1917
傲寒
傲寒 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.

提交回复
热议问题