是否可以使用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>
Run Code Online (Sandbox Code Playgroud)
我知道'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>
Run Code Online (Sandbox Code Playgroud)
从本质上讲,我要做的是拥有一个全局执行功能......
jQuery 1.7rc1的第614行:
window[ "eval" ].call( window, data );
为什么不简单写
eval.call( window, data );?