为什么 您不能使用 evalwith 陈述?

例如:

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

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

如果有人想知道我想提出的憎恶,这既需要“邪恶” evalwith - 我试图查看是否可以在另一个上下文中而不是定义的函数(用作回调)。 大概 (咳嗽)不会在任何地方使用它。.比什么都更好奇。

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

解决方案

这是仅从webkit的控制台重现的错误 eval 从一个 FunctionExpression.

当直接呼叫 eval 制作了,您期望的评估代码将同时共享可变环境:

(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 应在呼叫者的词汇环境中宣布,而不是在全球环境中宣布。

为了 FunctionDeclaration如果我们尝试的话,行为是完全正常的:

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上运行的以下浏览器上复制该问题:

  • Chrome 5.0.375.125
  • Chrome 6.0.472.25 Dev
  • Safari 5.0.1
  • WebKit夜间构建R64893

其他提示

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

function testfunc(a) { eval("alert(a)"); } testfunc("hello from a testfunc eval");

(function (a) { eval("alert(a)"); })("hello from a function constructor eval")

所有工作都很好: http://polyfx.com/jstest.html 在ff/chrome/safari/ie中。

从各种游戏机中运行代码段的问题是,控制台通常拧紧上下文。 (即,镀铬控制台似乎在全球上下文中没有正确包装物品,而firebug控制台确实没有正确包装)。它可能是一个错误,或者(更有可能)可以按预期工作。

评估总是在全球范围内运行,不是吗?

放出评估,除了撇开外,新的bwser包括ecma5函数。prototype.bind方法,以在某些选定对象的范围中调用函数。

对于较旧的浏览器,您可以伪造它 -

Function.prototype.bind= Function.prototype.bind || function bind(scope){
    var method= this;
    return function(){
        method.apply(scope, arguments);
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top