Index

no-implied-eval

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

在 JavaScript 中,避免使用 eval() 被认为是一种良好的做法。这么做涉及到安全性和性能方面的问题,这也是为什么许多代码检查工具(包括 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, setInterval, execScript*/

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"*/
/*global setTimeout, setInterval*/

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

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

选项

🌐 Options

此规则没有选项。

🌐 This rule has no options.

何时不使用

🌐 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 中引入。

资源