2011-08-25 35 views
3

好吧,我有一個非常具體的情況下,我需要使用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()函數,該函數已被棄用。它有效,但它讓我感到緊張。任何人都在關注這個問題?謝謝你的時間!

+3

我只想說,我喜歡你的樣品代碼的味道。 – Blazemonger

+0

@Alex:你有一個問題提到它'this.myString'?有關詳細討論,請參閱我的答案中的評論。 – Mrchief

回答

2

你可以說這樣的事情:

function mysteriousFunction(ctx) { 
    ctx.myString = "[value here]"; 
} 

mysteriousFunction(this); 
alert(myString);  // catch here: if you're using it in a anonymous function, you need to refer to as this.myString (see comments) 

演示:http://jsfiddle.net/mrchief/HfFKJ/

你也可以重構它是這樣的:

function mysteriousFunction() { 
    this.myString = "[value here]"; // we'll change the meaning of this when we call the function 
} 

然後call(雙關語意),你用功能不同的背景是這樣的:

var ctx = {}; 
mysteriousFunction.call(ctx); 
alert(ctx.myString); 

mysteriousFunction.call(this); 
alert(myString); 

演示:http://jsfiddle.net/mrchief/HfFKJ/4/

+0

它只適用於全球範圍。請參閱http://jsfiddle.net/cgKnF/。 –

+0

@Matthew:如果你聲明瞭一個匿名函數,那麼你必須調用'alert(this.myString)'。儘管如此,我在答案中更新了它。 http://jsfiddle.net/mrchief/cgKnF/1/ – Mrchief

+0

沒錯,但我認爲重點是他不想編寫'this.myString'。 –

1

jsFiddle

編輯:由於@Mathew非常和善指出我的代碼是沒有意義的!因此,使用字符串工作示例:

function mysteriousFunction(ctx) { 
    eval(ctx + ".myString = 'Our cruisers cant repel firepower of that magnitude!';"); 
} 
var obj = {}; 
mysteriousFunction("obj"); 
alert(obj.myString); 
+0

這沒有任何意義。如果你只是分配給窗口(不是最窄的範圍),爲什麼即使使用'eval'? –

0

我相當肯定這是不可能寫入功能範圍(即模擬var)從另一個功能,無需eval

請注意,當您通過this時,您要麼傳遞窗口,要麼傳遞一個對象。既沒有標識一個功能(非全局的範圍var)。