no-implied-eval

禁止使用类似 eval() 的方法

避免在 JavaScript 中使用 eval() 被认为是一种很好的做法。这样做涉及到安全和性能方面的问题,这就是为什么许多 linter(包括 ESLint)建议禁止 eval()。但是,还有其他一些方法可以传递字符串并将其解释为具有类似问题的 JavaScript 代码。

¥It’s considered a good practice to avoid using eval() in JavaScript. There are security and performance implications involved with doing so, which is why many linters (including ESLint) recommend disallowing eval(). However, there are some other ways to pass a string and have it interpreted as JavaScript code that have similar concerns.

第一种是使用 setTimeout()setInterval()execScript()(仅限 Internet Explorer),它们都可以接受一串 JavaScript 代码作为它们的第一个参数。例如:

¥The first is using setTimeout(), setInterval() or execScript() (Internet Explorer only), all of which can accept a string of JavaScript code as their first argument. For example:

setTimeout("alert('Hi!');", 100);

这被认为是隐含的 eval(),因为传入了一个 JavaScript 代码字符串以进行解释。setInterval()execScript() 也可以这样做。两者都在全局作用域内解释 JavaScript 代码。对于 setTimeout()setInterval(),第一个参数也可以是函数,这被认为更安全并且性能更高:

¥This is considered an implied eval() because a string of JavaScript code is passed in to be interpreted. The same can be done with setInterval() and execScript(). Both interpret the JavaScript code in the global scope. For both setTimeout() and setInterval(), the first argument can also be a function, and that is considered safer and is more performant:

setTimeout(function() {
    alert("Hi!");
}, 100);

最佳做法是始终将函数用于 setTimeout()setInterval() 的第一个参数(并避免 execScript())。

¥The best practice is to always use a function for the first argument of setTimeout() and setInterval() (and avoid execScript()).

规则详情

¥Rule Details

该规则旨在通过使用 setTimeout()setInterval()execScript() 来消除隐含的 eval()。因此,当任一函数使用字符串作为第一个参数时,它会触发警告。

¥This rule aims to eliminate implied eval() through the use of setTimeout(), setInterval() or execScript(). As such, it will warn when either function is used with a string as the first argument.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint no-implied-eval: "error"*/
/*global window*/

setTimeout("alert('Hi!');", 100);

setInterval("alert('Hi!');", 100);

execScript("alert('Hi!')");

window.setTimeout("count = 5", 10);

window.setInterval("foo = bar", 10);

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint no-implied-eval: "error"*/

setTimeout(function() {
    alert("Hi!");
}, 100);

setInterval(function() {
    alert("Hi!");
}, 100);

何时不使用

¥When Not To Use It

如果你想允许 setTimeout()setInterval() 带有字符串参数,那么你可以安全地禁用此规则。

¥If you want to allow setTimeout() and setInterval() with string arguments, then you can safely disable this rule.

版本

此规则是在 ESLint v0.0.7 中引入。

资源

ESLint 中文网
粤ICP备13048890号