简体   繁体   English

在函数字符串上使用 eval

[英]Using eval on a function string

I am doing :我在做 :

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

But that gives error :但这给出了错误:

Uncaught SyntaxError: Unexpected token (

Why is this wrong?为什么这是错误的?

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. eval运算符期望Program作为输入,而 JavaScript 的语法要求所有顶级程序元素要么是声明要么是语句。

The spec says:规范说:

Let prog be the ECMAScript code that is the result of parsing x as a Program.令 prog 是 ECMAScript 代码,它是将 x 解析为程序的结果。

function can't start a top-level statement, but it can start a function declaration, but only when it has a name. function不能开始顶级语句,但可以开始函数声明,但前提是它有名字。

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.正如其他人所指出的,要对eval值,您需要欺骗 JavaScript 解析器在它需要语句的地方找到一个表达式。 Wrapping the body in parentheses is one way to do this.将正文括在括号中是执行此操作的一种方法。

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方法:

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.您的主要错误是试图通过在eval方法调用的末尾添加括号来调用eval返回的内容。 If you want the function your passing to immediately invoke itself, the added parenthesis should be part of the thing your passing to eval .如果您希望传递的函数立即调用自身,则添加的括号应该是传递给eval

I'm assuming you're trying to do something other than call "Hello World", as you could simply do this:我假设您正在尝试执行除“Hello World”以外的其他操作,因为您可以简单地执行以下操作:

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

Or, dare I say:或者,我敢说:

console.log("Hello World");

eval expects a statement but: eval需要一个声明,但是:

  • function(){} is not valid as a statement because the function name is missing. function(){}作为语句无效,因为缺少函数名称。

  • (function(){}) is instead recognized because the statement is a "statement expression". (function(){})被识别,因为该语句是“语句表达式”。

The problem is that function as first token triggers the function declaration rule when a statement is expected.问题是, function作为第一个标记时触发的声明预计在函数声明规则。 When an expression is expected instead (eg inside parenthesis) then function triggers the function expression rules where a name is optional but not mandatory.当需要一个表达式时(例如在括号内),则function会触发函数表达式规则,其中名称是可选的但不是强制性的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM