Home  >  Article  >  Web Front-end  >  JavaScript Advanced Series—Why not to use eval

JavaScript Advanced Series—Why not to use eval

黄舟
黄舟Original
2017-02-08 09:40:361348browse
  • Disguised eval

  • Security issues

  • ##Conclusion

  • ## The #eval function executes a string of JavaScript code in the current scope.
var foo = 1;
function test() {
    var foo = 2;
    eval('foo = 3');
    return foo;
}
test(); // 3
foo; // 1

But eval is only executed in the current scope when it is called directly and the calling function is eval itself.

var foo = 1;
function test() {
    var foo = 2;
    var bar = eval;
    bar('foo = 3');
    return foo;
}
test(); // 2
foo; // 3

Translator's Note: The above code is equivalent to calling eval in the global scope, and has the same effect as the following two writing methods:

// 写法一:直接调用全局作用域下的 foo 变量
var foo = 1;
function test() {
    var foo = 2;
    window.foo = 3;
    return foo;
}
test(); // 2
foo; // 3

// 写法二:使用 call 函数修改 eval 执行的上下文为全局作用域
var foo = 1;
function test() {
    var foo = 2;
    eval.call(window, 'foo = 3');
    return foo;
}
test(); // 2
foo; // 3

We should avoid using eval under any circumstances function. 99.9% of scenarios that use eval have solutions that don't use eval.

Disguised eval

The timing functions setTimeout and setInterval both accept strings as their first parameter. This string is always executed in the global scope, so eval is not called directly in this case.

Security Issues

eval also has security issues because it will execute any code passed to it. Never use eval when the code string is unknown or comes from an untrusted source. function.

Conclusion

Never use eval, any code that uses it will be questionable in terms of how it works, performance and security. If some situation requires the use of eval to work properly, first of all its design will be questioned and it should not be the preferred solution. A better solution that does not use eval should be fully considered and adopted first.

The above is the JavaScript advanced series - why not to use eval. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn