的JavaScript等同於VBScript的執行[全球]是的eval()。通過的代碼在調用的上下文中進行評估。
見here for details, pros and cons
UPDATE
不建議這種做法,而是要澄清我的等值的理解:
// calling eval in global context is the exact equivalent of ExecuteGlobal
eval("function f0() {print('f0(): yes, we can!');}");
f0();
// calling eval in locally is the exact equivalent of Execute
function eval00() {
eval("function f1() {print('f1(): no, we can not!');}");
f1();
}
eval00();
try {
f1();
}
catch(e) {
print("** error:", e.message);
}
// dirty trick to affect global from local context
function eval01() {
eval("f2 = function() {print('f2(): yes, we can use dirty tricks!');}");
f2();
}
eval01();
f2();
輸出:
js> load("EvalDemo.js")
f0(): yes, we can!
f1(): no, we can not!
** error: "f1" is not defined.
f2(): yes, we can use dirty tricks!
f2(): yes, we can use dirty tricks!
所以存在的問題這可以使用VBScript中的Execute [Global]來解決,可以使用Javascript中的eval()來解決;對於某些問題,可能需要額外的工作或技巧。
正如Abhishek明確表示「我想在JavaScript中評估JavaScript」,我不覺得有必要證明我的答案。
如果有東西執行一個字符串作爲代碼,解決方案是重構它,所以它不。你不應該把代碼保存在字符串中。 – Quentin 2012-07-13 09:35:33
你「可以」使用'setTimeout(code,0)'...但你確定你真的需要這個嗎?我同意昆汀在這裏。 – 2012-07-13 09:35:55
@FelixKling - 我打算建議(有可怕的警告),但是在大多數JS引擎中有一個最小超時時間,並且它會異步評估代碼。 – Quentin 2012-07-13 09:38:00