2012-03-23 69 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