是否可以使用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)
从本质上讲,我要做的是拥有一个全局执行功能......
orc*_*rca 39
(function(){
eval.apply(this, arguments);
}(a,b,c))
Run Code Online (Sandbox Code Playgroud)
这将window在浏览器中使用全局对象调用eval ,作为this传递您传递给匿名函数的任何参数的参数.
eval.call(window, x, y, z)或者eval.apply(window, arguments)如果你确定window是全局对象也是有效的.然而,这并非总是如此.例如,process如果我没记错的话,Node.js脚本中的全局对象就是这样.
使用(1, eval)('...').
$ node
> fooMaker = function () { (1, eval)('foo = "bar"'); };
[Function]
> typeof foo
'undefined'
> fooMaker()
undefined
> typeof foo
'string'
> foo
'bar'
Run Code Online (Sandbox Code Playgroud)
我知道会有很多评论说 eval 是邪恶的,我同意这一点。但是,要回答您的问题,请更改您的启动方法,如下所示:
function start(){
execute("ary = new Array()");
execute("ary.push('test');"); // This will cause exception: ary is not defined
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16618 次 |
| 最近记录: |