2012-03-23 67 views
2

我知道使用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 
}​; 

+0

close voter - 这是如何过于本地化? – 2012-03-23 03:08:01

回答

0

here's a demo让你有任何代码,它包含一个函数,将作为您的命名空间。然后将该函数返回到作为变量存储的外部世界。 this demo显示了它如何构建,但是,只有在代码是以对象字面符号表示时才有效。

window.onload = function() { 
    'use strict'; 

    var ns = 'lol'; 

    //code must be an object literal 
    var code = '{name: "Spock",greeting: function(){return "Hello " + foo.name;}}'; 

    //store in a constructor to be returned 
    var constructorString = 'var ns = function(){return ' + code + '}; ns'; 

    var evalNs = eval(constructorString);  //type function/constructor 
    var evalObj = new evalNs()    //object instance 

    console.log(evalNs); //constructor 
    console.log(evalObj); //the namespaced object 
    console.log(ns);  //outer "ns" preserved 
};​ 

+0

这似乎工作。然而,当代码是这样的函数时会发生什么?Dog(){this。this = this(){} {return}'Hello world'; } this.dontgreet = function(){ return'hello world'; } }另外它将如何处理多行代码?我无法使用上面粘贴的示例。有任何想法吗 ?不知何故,这个评论搞砸了上面的代码格式,但它的多行。 – ssarangi 2012-03-23 03:24:13

+0

更新了我的代码。这是概念的证明,但具有任意代码是真的有风险 – Joseph 2012-03-23 03:35:03

+0

我同意。任意代码是有风险的。然而,目的是一种小小的东西,我们可以对对象进行反思。我看到你是如何实现这个的,但是如果我们使用函数Dog(),而不是你的例子,我会在运行eval时遇到以下错误 - '缺少:属性ID'后'。 - http://pastebin.com/s6r5wjdc(这是我例子中的constructorString)。 http://jsfiddle.net/DbrEF/7/ – ssarangi 2012-03-23 03:44:34

0

您可能需要使用JavaScript分析器,就像JSHint/JSLint的使用的一个

+0

啊,这是我试图避免这一点。 – ssarangi 2012-03-23 03:10:14

2

在2015年,creating a Function object是你最好的选择在这里,而不是使用eval更好的运气:

(new Function('arg1','arg2',"return arg1+arg2")(3,4) // returns 7