Home > Web Front-end > JS Tutorial > body text

JavaScript Advanced Series—Why not to use eval

黄舟
Release: 2017-02-08 09:40:36
Original
1341 people have browsed it
  • 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
Copy after login

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
Copy after login

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
Copy after login

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)!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!