【发布时间】:2020-06-08 02:17:20
【问题描述】:
前言:在 JavaScript 中使用 with 是 discouraged 是有充分理由的。它可能导致混乱的代码和前向兼容性问题(例如,将新属性添加到内置对象时)。这个问题不是关于是否应该使用with - 它是关于with 的规范定义的行为。
下面的代码应该工作吗?
let foo = {};
with(foo) {
function bar() {
console.log("hello");
}
}
bar();
它适用于 Chrome 80,但不适用于 Firefox 72:TypeError: bar is not a function。
编辑:原来这个错误只在粘贴到 Firefox 控制台 (https://i.imgur.com/WTG3iiX.png) 时发生,而不是在 HTML 文档中运行代码时发生。
但请注意,它是TypeError,而不是ReferenceError(即bar is not defined)。为了确认这一点,我们可以在bar(); 之前添加console.log("bar" in window),并注意在Firefox 中输出true,而如果你在代码之前编写它会输出false。所以在 Firefox 中,上述代码具有将window.bar 设置为undefined 的效果。
这在 Firefox 和 Chrome 中都可以正常工作:
if(true) {
function bar() {
console.log("hello");
}
}
bar();
正如我所料,因为function foo() {...} 声明是函数作用域的。因此,除非with 块作用域有什么奇怪的地方,否则这似乎是一个 Firefox 错误?
【问题讨论】:
标签: javascript firefox scope with-statement