在函数字符串上使用eval [英] Using eval on a function string
问题描述
我正在做:
eval('function(){ console.log("Hello World"); }')();
但这会产生错误:
Uncaught SyntaxError: Unexpected token (
为什么这是错的?
推荐答案
eval
运算符需要程序为输入和JavaScript的语法要求所有
顶级程序元素都是声明或语句。
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.
规范说:
让编程是ECMAScript代码,它是将x解析为程序的结果。
Let prog be the ECMAScript code that is the result of parsing x as a Program.
function
无法启动顶级语句,但它可以启动一个函数声明,但只有当它有一个名字。
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.
正如其他人所说, eval
很有趣ction,你需要欺骗JavaScript解析器找到一个需要语句的表达式。用括号包裹身体是一种方法。
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.
这篇关于在函数字符串上使用eval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!