eval函数是一种强大而简单的动态生成代码的方法,那么有什么注意事项呢?
当前回答
不恰当地使用eval会打开你的 注入攻击代码 调试可能更具挑战性 (没有行号等) 经过评估的代码执行速度较慢(没有机会编译/缓存经过评估的代码)
编辑:正如杰夫·沃尔登在评论中指出的那样,第三条在今天已经不像2008年那么正确了。然而,虽然可能会发生一些已编译脚本的缓存,但这将只局限于没有修改地重复计算的脚本。更可能的情况是,您正在计算的脚本每次都经历了轻微的修改,因此无法缓存。我们就说someeval代码执行得更慢。
其他回答
如果你想让用户输入一些逻辑函数并计算与或,那么JavaScript的eval函数是完美的。我可以接受两个字符串和eval(ate) string1 === string2等。
我相信这是因为它可以从字符串执行任何JavaScript函数。使用它可以使人们更容易向应用程序中注入恶意代码。
这是一篇谈论eval的好文章,以及它如何不是一种邪恶: http://www.nczonline.net/blog/2013/06/25/eval-isnt-evil-just-misunderstood/
I’m not saying you should go run out and start using eval() everywhere. In fact, there are very few good use cases for running eval() at all. There are definitely concerns with code clarity, debugability, and certainly performance that should not be overlooked. But you shouldn’t be afraid to use it when you have a case where eval() makes sense. Try not using it first, but don’t let anyone scare you into thinking your code is more fragile or less secure when eval() is used appropriately.
主要是,维护和调试要困难得多。就像goto一样。您可以使用它,但它会使发现问题变得更加困难,对稍后可能需要进行更改的人来说也更加困难。
和其他答案一样,我不认为eval语句可以有高级最小化。