[英]Javascript eval on global scope?
是否可以使用 eval 命令在全局范圍內執行某些操作? 例如,這將導致錯誤:
<script>
function execute(x){
eval(x);
}
function start(){
execute("var ary = new Array()");
execute("ary.push('test');"); // This will cause exception: ary is not defined
}
</script>
<html><body onLoad="start()"></body></html>
我知道 'with' 關鍵字會設置一個特定的范圍,但是有全局范圍的關鍵字嗎? 或者是否可以定義一個允許它工作的自定義范圍?
<script>
var scope = {};
function execute(x){
with(scope){
eval(x);
}
}
function start(){
execute("var ary = new Array()");
execute("ary.push('test');"); // This will cause exception: ary is not defined
}
</script>
<html><body onLoad="start()"></body></html>
本質上,我想要做的是擁有一個全局執行函數......
(function(){
eval.apply(this, arguments);
}(a,b,c))
這將使用全局對象、瀏覽器中的window
調用 eval,因為this
參數傳遞您傳遞給匿名函數的任何參數。
如果您確定window
是全局對象eval.call(window, x, y, z)
或eval.apply(window, arguments)
也是有效的。 然而,這並不總是正確的。 例如,如果我沒記錯的話,Node.js 腳本中的全局對象是process
。
使用(1, eval)('...')
。
$ node
> fooMaker = function () { (1, eval)('foo = "bar"'); };
[Function]
> typeof foo
'undefined'
> fooMaker()
undefined
> typeof foo
'string'
> foo
'bar'
您應該能夠通過間接調用在全局范圍內使用eval()
。 但是,目前並非所有瀏覽器都這樣做。
要在全局范圍內執行一些 JavaScript,您可以使用setTimeout()間接調用它,或者如果您使用的是 jQuery,請查看$.globalEval() 。
將您的執行方法更改為以下內容將允許您仍然使用“var”關鍵字:
function execute(x) {
setTimeout("eval(" + x + ")", 0);
// Or: $.globalEval(x);
}
function start() {
try
{
execute("var ary = new Array()");
execute("ary.push('test');");
}
catch (e)
{
alert(e);
}
}
start();
使用eval.apply(null, ["code"]);
.
eval.apply(this, ["code"]);
不適用於 Microsoft 腳本宿主 (cscript.exe)。
示例:
> type test.js
eval.apply(null, ["a=3;"]);
WScript.Echo(a);
> cscript test.js
Microsoft (R) Windows Script Host 버전 5.812
Copyright (C) Microsoft Corporation. All rights reserved.
3
我知道會有很多關於 eval is evil 的評論,我同意這一點。 但是,要回答您的問題,請按如下方式更改啟動方法:
function start(){
execute("ary = new Array()");
execute("ary.push('test');"); // This will cause exception: ary is not defined
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.