eval函数是一种强大而简单的动态生成代码的方法,那么有什么注意事项呢?
当前回答
编辑:正如Benjie的评论所建议的,这似乎不再是chrome v108的情况,似乎chrome现在可以处理已计算脚本的垃圾收集。
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
垃圾收集
浏览器的垃圾收集不知道被评估的代码是否可以从内存中删除,所以它只是一直存储它,直到页面被重新加载。 如果你的用户只是在你的页面上停留很短的时间,这不是太糟糕,但这可能是一个webapp的问题。
下面是演示该问题的脚本
https://jsfiddle.net/CynderRnAsh/qux1osnw/
document.getElementById("evalLeak").onclick = (e) => {
for(let x = 0; x < 100; x++) {
eval(x.toString());
}
};
像上面代码这样简单的代码会导致存储少量内存,直到应用程序死亡。 当被赋值的脚本是一个巨大的函数,并且在间隔时间调用时,情况会更糟。
其他回答
主要是,维护和调试要困难得多。就像goto一样。您可以使用它,但它会使发现问题变得更加困难,对稍后可能需要进行更改的人来说也更加困难。
不恰当地使用eval会打开你的 注入攻击代码 调试可能更具挑战性 (没有行号等) 经过评估的代码执行速度较慢(没有机会编译/缓存经过评估的代码)
编辑:正如杰夫·沃尔登在评论中指出的那样,第三条在今天已经不像2008年那么正确了。然而,虽然可能会发生一些已编译脚本的缓存,但这将只局限于没有修改地重复计算的脚本。更可能的情况是,您正在计算的脚本每次都经历了轻微的修改,因此无法缓存。我们就说someeval代码执行得更慢。
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
编辑:正如Benjie的评论所建议的,这似乎不再是chrome v108的情况,似乎chrome现在可以处理已计算脚本的垃圾收集。
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
垃圾收集
浏览器的垃圾收集不知道被评估的代码是否可以从内存中删除,所以它只是一直存储它,直到页面被重新加载。 如果你的用户只是在你的页面上停留很短的时间,这不是太糟糕,但这可能是一个webapp的问题。
下面是演示该问题的脚本
https://jsfiddle.net/CynderRnAsh/qux1osnw/
document.getElementById("evalLeak").onclick = (e) => {
for(let x = 0; x < 100; x++) {
eval(x.toString());
}
};
像上面代码这样简单的代码会导致存储少量内存,直到应用程序死亡。 当被赋值的脚本是一个巨大的函数,并且在间隔时间调用时,情况会更糟。
我不会试图反驳之前所说的任何事情,但我将提供eval()的这种用法,(据我所知)不能以任何其他方式完成。可能还有其他方法来编码,也可能有其他方法来优化它,但这是直接完成的,为了清晰起见,没有任何花哨的东西来说明eval的使用,这真的没有任何其他选择。也就是说:动态(或者更准确地说)编程创建的对象名称(相对于值)。
//Place this in a common/global JS lib:
var NS = function(namespace){
var namespaceParts = String(namespace).split(".");
var namespaceToTest = "";
for(var i = 0; i < namespaceParts.length; i++){
if(i === 0){
namespaceToTest = namespaceParts[i];
}
else{
namespaceToTest = namespaceToTest + "." + namespaceParts[i];
}
if(eval('typeof ' + namespaceToTest) === "undefined"){
eval(namespaceToTest + ' = {}');
}
}
return eval(namespace);
}
//Then, use this in your class definition libs:
NS('Root.Namespace').Class = function(settings){
//Class constructor code here
}
//some generic method:
Root.Namespace.Class.prototype.Method = function(args){
//Code goes here
//this.MyOtherMethod("foo")); // => "foo"
return true;
}
//Then, in your applications, use this to instantiate an instance of your class:
var anInstanceOfClass = new Root.Namespace.Class(settings);
编辑:顺便说一下,我不建议(出于之前指出的所有安全原因)根据用户输入来确定对象名称。但我想不出你有什么理由这么做。不过,我还是想指出这不是一个好主意:)