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