为什么eval无法访问with语句下的作用域变量? [英] How come eval doesn't have access to the scoped variables under a with statement?

查看:102
本文介绍了为什么eval无法访问with语句下的作用域变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么无法使用 eval 下使用语句访问范围变量?

Why can't you access scoped variables using eval under a with statement?

例如:

(function (obj) { 
   with (obj) {
      console.log(a); // prints out obj.a
      eval("console.log(a)"); // ReferenceError: a is not defined
   }
})({ a: "hello" })

EDIT :正如知识渊博的CMS所指出的那样,这似乎是一个浏览器错误(使用WebKit控制台的浏览器)。

EDIT: As the knowledgeable CMS pointed out, this appears to be a browser bug (browsers that use the WebKit console).

如果有人想知道我试图想出的那种令人厌恶的东西需要邪恶的 eval 以及 - 我当时试图看看我是否可以获得在另一个上下文中执行的函数(用作回调),而不是在其中定义的函数。并且不,我可能(咳嗽)不会在任何地方使用它。比任何事都好奇。

If anyone was wondering what abomination I was trying to come up with that would require both the "evil" eval and with -- I was trying to see if I could get a function (used as a callback) executed in another context rather than the one it was defined in. And no, I probably (cough) won't use this anywhere.. more curious than anything.

(function (context,fn) { 
    with (context) 
       eval("("+fn+")()"); 
})({ a: "hello there" }, function () { console.log(a); })


推荐答案

这是一个只能从WebKit的控制台重现的错误,它在 eval 从 FunctionExpression 调用。

This is a bug reproducible only from the WebKit's Console, it has problems binding the caller context when eval is invoked from a FunctionExpression.

直接调用 eval 已经完成,您所期望的评估代码应该共享变量环境:

When a direct call of eval is made, the evaluated code as you expect should share both the variable environment:

(function (arg) {
  return eval('arg');
})('foo');
// should return 'foo', throws a ReferenceError from the WebKit console

还词汇环境:

(function () {
  eval('var localVar = "test"');
})();

typeof localVar; // should be 'undefined', returns 'string' on the Console

在上面的函数中 localVar 应该在调用者的词汇环境中声明,而不是在全局上下文中声明。

In the above function localVar should be declared on the lexical environment of the caller, not on the global context.

对于 FunctionDeclaration s行为完全正常,如果我们尝试:

For FunctionDeclarations the behavior is completely normal, if we try:

function test1(arg) {
  return eval('arg');
}
test1('foo'); // properly returns 'foo' on the WebKit console

function test2() {
  eval('var localVarTest = "test"');
}
test2();
typeof localVarTest; // correctly returns 'undefined'

我已经能够在以下运行的浏览器上重现该问题Windows Vista SP2:

I have been able to reproduce the problem on the following browsers running on Windows Vista SP2:


  • Chrome 5.0.375.125

  • Chrome 6.0.472.25 dev

  • Safari 5.0.1

  • WebKit每晚构建r64893

  • Chrome 5.0.375.125
  • Chrome 6.0.472.25 dev
  • Safari 5.0.1
  • WebKit Nightly Build r64893

这篇关于为什么eval无法访问with语句下的作用域变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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