Eval
On this page
JavaScript Eval (JavaScript评估)
In this chapter, you will see how a JavaScript built-ineval() function works.
Normally, it is used for evaluating a JavaScript code, which is represented as a string.
(在本章中,您将看到JavaScript built-ineval ()函数的工作原理。
通常,它用于评估JavaScript代码,该代码表示为字符串。)
The syntax of the eval() function is the following:
let result = eval(code);
For a better perception, you can check out the following example:
let code = 'console.log("Welcome to w3cdoc")';
eval(code); // Welcome to w3cdoc
Eval is considered a function property of the global object. (Eval被视为全局对象的函数属性。)
As a rule, the eval() function’s argument is a string. In case the latter presents an expression, eval()will evaluate it. In case an argument presents one and more statements, then eval()will evaluate the statements. (通常, eval ()函数的参数是一个字符串。 如果后者呈现表达式, eval ()将对其进行求值。 如果参数显示一个或多个语句,则eval ()将计算这些语句。)
You shouldn’t call this function for evaluating an arithmetic expression, as JavaScript evaluates them automatically. In the cases when the argument is not a string, eval() will return the argument unchanged. Here is an example:
console.log(eval(new String('1 + 2'))); // returns a String object containing "1 + 2"
console.log(eval('1 + 2')); // returns 3
Such a limitation can be worked around with the help of toString() like this:
let exp = new String('1 + 2');
console.log(eval(exp.toString())); // returns 3
Generally, eval’s result is equivalent to the result of the last statement. It is demonstrated below:
let value1 = eval('1+2');
console.log(value1); // 3
let value2 = eval('let i = 1; ++i');
console.log(value2); // 2
In case the code is executed within the current lexical environment, outer variables can be seen by it:
let val = 1;
function fn() {
let val = 10;
eval('console.log(val)'); // 10
}
fn();
In addition, those variables can be modified by it:
let x = 10;
eval("x = 20");
console.log(x); // 10, value modified
Eval has its own lexical environment in the strict mode. So, no one can see the functions and variables, declared in it:
//'use strict' is enabled in runnable examples by default
eval("let x = 10; function fn() {}");
console.log(typeof x); // undefined, no such variable
// function fn is not visible
Be Careful with Eval!
Be Careful with Eval! (小心Eval !)
It is essential to note that eval() is quite a dangerous function. That’s why in modern programming the phrase “eval is evil” is so actual. So, using it is a bad practice for a programmer. (需要注意的是eval ()是一个相当危险的函数。这就是为什么在现代编程中, “eval is evil”这个短语如此真实。因此,使用它对程序员来说是一种糟糕的做法。)
In case you run it with a string, which may be impacted by a malicious party, it can lead to malicious code on the user’s device with the permissions of your page or extensions. (如果您使用可能受到恶意方影响的字符串运行它,则可能会导致用户设备上具有页面或扩展程序权限的恶意代码。)
Luckily, in modern JavaScript, there is an opportunity to replace it with JavaScript Module or other modern language constructs. (幸运的是,在现代JavaScript中,有机会用JavaScript模块或其他现代语言结构替换它。)