我知道使用eval并不推荐,我也阅读过此链接。 Set Variable inside Eval (JavaScript)使用Javascript中的“eval”运行的代码的访问变量
但是,这是我想要做的。假设我们在文本框中有一些代码。所以我必须把这些文本,然后找出代码中的所有全局变量,函数和对象。 我的想法是将代码包装在命名空间中,对它进行评估,然后遍历命名空间的属性以获取结果。但是,即使eval成功运行,我也无法访问在此定义的变量。有没有更好的解决方案或其他方式来实现这一目标。
http://jsfiddle.net/DbrEF/2/ - 这是这里的小提琴。
“var code”实际上可以是任意代码。我知道它不安全,但我需要它来适应不同的环境。 由于对安全使用eval使用"use strict"
window.onload = function(){
'use strict';
//use strict forces to run code in "strict mode"
//use strict prevents eval from
//contaminating the immediate scope
//let's test with "foo"
var foo = 'lol';
//now code has "foo" but using "use strict"
//makes code in eval stay in eval
//note that at the last of the code, foo is "returned"
var code = 'var foo = {name: "Spock",greeting: function() {return "Hello " + foo.name;}}; foo';
//store eval'ed code in evalO
var evalstore = eval(code);
console.log(evalstore); //code in eval stays in here, which is "inner foo"
console.log(foo); //"outer foo" is unharmed and daisy fresh
};
close voter - 这是如何过于本地化? – 2012-03-23 03:08:01