全球范围内的Javascript评估?

wun*_*tee 32 javascript 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>
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脚本中的全局对象就是这样.

  • `eval.call(windwow,X); `为我工作,跨浏览器实施.原因是,全局范围应该始终是`window`对象,随后定义的函数将属于这个对象,例如`JSON.stringify`只不过是`window ['JSON'] ['stringify']`和事件`window ['window'] ['window'] ['window'] ['window'] ['JSON'] ['stringify']`; 两者仍然有效. (3认同)
  • -1.请阅读http://perfectionkills.com/global-eval-what-are-the-options/了解真实情况. (3认同)

ale*_*lex 6

您应该可以eval()通过间接调用它来在全局范围内使用.但是,并非所有浏览器目前都在这样做.

进一步阅读.


pyr*_*ade 5

使用(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)

  • 我不确定这是什么样的黑魔法,但它的效果非常好.我很想知道这里到底发生了什么,你能解释一下吗?:) (3认同)

Cha*_*ndu 1

我知道会有很多评论说 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)