好吧,我有一個非常具體的情況下,我需要使用eval()。在人們告訴我不應該使用eval()之前,讓我透露一下我知道eval的性能問題,安全問題以及所有爵士樂。我在非常狹窄的情況下使用它。問題是這樣的:Javascript:使全局eval()的行爲像object.eval()
我尋求將寫一個變量的任何範圍傳遞給它,允許這樣的代碼的函數:
function mysteriousFunction(ctx) {
//do something mysterious in here to write
//"var myString = 'Oh, I'm afraid the deflector shield will be
//quite operational when your friends arrive.';"
}
mysteriousFunction(this);
alert(myString);
我使用全局的eval嘗試()做這個,僞造執行上下文與關閉,'與'關鍵字等等我不能讓它工作。我發現的唯一的作品是:
function mysteriousFunction(ctx) {
ctx.eval("var myString = 'Our cruisers cant repel firepower of that magnitude!';");
}
mysteriousFunction(this);
alert(myString); //alerts 'Our cruisers cant repel firepower of that magnitude!'
但是,上述解決方案需要object.eval()函數,該函數已被棄用。它有效,但它讓我感到緊張。任何人都在關注這個問題?謝謝你的時間!
我只想說,我喜歡你的樣品代碼的味道。 – Blazemonger
@Alex:你有一個問題提到它'this.myString'?有關詳細討論,請參閱我的答案中的評論。 – Mrchief