9

1. What is the use of the eval function?

The eval function can be called, and its parameters can be interpreted as a javascript program. In other words, eval can treat its parameters as code

To execute.

example

function f(x) {
    eval('var y=x');
    console.log('y:', y);
}
f('hello');//y:hello

In this example, eval it is string parameters var y=x performed as a line of code, the function f inside declare a local variable y . with

function f(x) {
    var y=x;
    console.log('y:', y);
}
f('hello');//y:hello

The effect of implementation is basically the same.

2. Avoid using the eval function to create local variables

​ It is quite wrong to allow the eval function to interfere with the scope. This approach makes a piece of code difficult to understand and no longer safe. The following example gives the external caller the ability to modify local variables and change the local scope.

example

let g = '全局变量'
function f(src) {
    eval(src);
    console.log('g:', g);
}
//以上为源代码
f("var g= '局部变量'");//g:局部变量
f("var y= '局部变量'");//g:全局变量

y that is not defined in the source code into the eval function, the result of this code execution will become unpredictable.

An easy way to ensure that the eval function does not affect the outer scope is to use nested scopes. ES5's strict mode does this.

example

let g = '全局变量'
function f(src) {
   (()=> eval(src))();//在嵌套作用域中执行eval
    console.log('g:', g);
}
//以上为源代码
f("var g= '局部变量'");//g:全局变量
f("var y= '局部变量'");//g:全局变量

3. Two calling methods of eval function

3.1 Direct call method:

When a function call involves the eval identifier, it can be called a direct call. At this point, the executed program (eval parameter) has full access to the local scope of the caller.

example

const g = '全局变量';
function foo() {
    const g = '局部变量';
    console.log(eval('g'));//直接调用,可以访问到foo的局部作用域,所以输出的是局部变量g
}
foo(); //局部变量

3.2 Indirect call method:

Bind eval to another variable name, and call eval through this variable, which is called an indirect call. At this time, the executed program (eval parameter) loses access to the local scope. Using the comma operator , , the concise writing of indirect calls can be realized.

example

const g = '全局变量';
function foo2() {
    const g = '局部变量';
    cont test = eval;
    //间接调用,不能访问函数内部的变量g
    console.log(test('g')); //全局变量
    //间接调用简洁方式
    console.log((0, eval)('g'));//全局变量
}

forceddd
271 声望912 粉丝

一名前端爱好者。