Javascript eval 在全局范围内? [英] Javascript eval on global scope?

查看:28
本文介绍了Javascript eval 在全局范围内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 eval 命令在全局范围内执行某些操作?例如,这将导致错误:

Is it possible to use the eval command to execute something with a global scope? For example, this will cause an error:

<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' 关键字会设置一个特定的范围,但是否有全局范围的关键字?或者是否可以定义一个自定义范围来允许它工作?

I know the 'with' keyword will set a specific scope, but is there a keyword for the global scope? Or is it possible to define a custom scope that would allow this to work?

<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>

本质上,我想做的是有一个全局执行函数...

Essentially, what I am trying to do is have a global execute funciton...

推荐答案

(function(){
    eval.apply(this, arguments);
}(a,b,c))

这将在浏览器中使用全局对象 window 调用 eval,因为 this 参数传递您传递给匿名函数的任何参数.

This will invoke eval using the global object, window in browsers, as the this argument passing any arguments you've passed into the anonymous function.

eval.call(window, x, y, z)eval.apply(window, arguments) 如果你确定 window 也是有效的 是全局对象.然而,这并不总是正确的.例如,如果我没记错的话,Node.js 脚本中的全局对象是 process.

eval.call(window, x, y, z) or eval.apply(window, arguments) is also valid if you're certain window is the global object. This isn't always true, however. For instance, the global object in a Node.js script is process if I remember correctly.

这篇关于Javascript eval 在全局范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆