问题描述
我在函数中错误地将参数重新声明为 const
,而不是抛出 SyntaxError:标识符'bar'已经被声明
ReferenceError:未定义栏.
.
I mistakenly wrote a re-declaration of an argument as a const
in a function and instead of throwing SyntaxError: Identifier 'bar' has already been declared
I ended up with ReferenceError: bar is not defined.
.
是什么原因导致这种行为?这不是预期的错误,让我困惑了几分钟.
What causes this behaviour? It wasn't the expected error, and left me confused for a few minutes.
示例代码:
function foo(bar) {
try {
console.log(bar);
const bar = 123;
} catch(err) { console.log(err) }
}
foo(456);
如果我不将声明包装在try/catch中,则会得到(我相信是)预期的错误.
If I don't wrap the declaration in a try/catch, I get (what I believe to be) the expected error.
推荐答案
来自此MDN文章.
由于您将 bar
包裹在一个括号中,因此其定义是相对于该括号的.并且由于在该块中还有另一个 bar
声明,尽管在调用之后,该编译器仍将尝试使用此新定义的 bar
而不是传入的范围.将它们重命名为单独的参数以减轻混乱,因为您可能会因为声明而认为它们保存着不同的数据.
Since you wrapped bar
inside a block of braces, its definition is relative to that block. And because you have another bar
declaration inside of that block, despite being after the call to it, the compiler will attempt to use this newly defined bar
instead of the passed-in parameter. Rename them as separate parameters to mitigate confusion, since one can assume they are holding different data because of your declaration.
这篇关于为什么在try/catch中重新声明参数会引发ReferenceError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!