eval函数是一种强大而简单的动态生成代码的方法,那么有什么注意事项呢?


当前回答

主要是,维护和调试要困难得多。就像goto一样。您可以使用它,但它会使发现问题变得更加困难,对稍后可能需要进行更改的人来说也更加困难。

其他回答

我相信这是因为它可以从字符串执行任何JavaScript函数。使用它可以使人们更容易向应用程序中注入恶意代码。

除非您100%确定正在评估的代码来自可信的来源(通常是您自己的应用程序),否则这将使您的系统暴露于跨站点脚本攻击。

如果您正在执行用户提交的代码,除了可能存在的安全问题之外,大多数情况下,有一种更好的方法,无需在每次执行时都重新解析代码。匿名函数或对象属性可以替代eval的大部分用途,而且更安全、更快。

需要记住的一件事是,您可以经常使用eval()在其他受限制的环境中执行代码——阻塞特定JavaScript函数的社交网站有时可以通过在eval块中分解它们来愚弄它们

eval('al' + 'er' + 't(\'' + 'hi there!' + '\')');

因此,如果你想运行一些JavaScript代码,否则它可能是不允许的(Myspace,我看着你…),那么eval()可能是一个有用的技巧。

然而,由于上面提到的所有原因,你不应该在你自己的代码中使用它,在那里你有完全的控制权——这是没有必要的,最好把它归到“棘手的JavaScript hacks”架子上。

eval() is very powerful and can be used to execute a JS statement or evaluate an expression. But the question isn't about the uses of eval() but lets just say some how the string you running with eval() is affected by a malicious party. At the end you will be running malicious code. With power comes great responsibility. So use it wisely is you are using it. This isn't related much to eval() function but this article has pretty good information: http://blogs.popart.com/2009/07/javascript-injection-attacks/ If you are looking for the basics of eval() look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval