不一致的“与”行为-没有访问功能-这是一个chrome的错误

Inconsistent `with` behavior - no access within functions - is this a chrome bug?

本文关键字:错误 chrome 一个 访问 行为 不一致 功能      更新时间:2023-09-26

让我们暂时停止"不要使用with"的合唱,并假设我有一个合法的用例*。如果我有这个代码

with({x: "hi"}) {
  console.log("outside x is", x);
  function aFunc() {
    console.log("inside a func x is", x);
  }
  aFunc();
}

在IE11和Firefox中,这两个语句都打印"hi"。在chrome中,我在循环中得到x上的ReferenceError

哪个是正确的行为?这是chrome浏览器的bug吗?


*。用例是,我正在制作一个浏览器内IDE环境,允许用户在提供额外功能的同时输入javascript,并且不想将函数直接附加到全局作用域(想想jsbin/jsfiddle,但用于特定任务)。

哪个是正确的行为?

没有指定。问题是你的代码:你有一个with块内的函数声明,这是无效的。函数声明必须是顶级程序/函数代码。

在Kangax的优秀网站上阅读更多关于块中的函数声明以及它们在不同浏览器中是如何处理的。

这是一个chrome bug吗?

。将代码更改为

with({x: "hi"}) {
  console.log("outside x is", x);
  var aFunc = function() {
    console.log("inside a func x is", x);
  }
  aFunc();
}

一个IEFE也应该工作:

with({x: "hi"}) (function(){
  console.log("outside x is", x);
  function aFunc() {
    console.log("inside a func x is", x);
  }
  aFunc();
}());