JavaScript:使用严格模式在try / catch中定义一个常量 [英] JavaScript: define a constant inside try / catch with strict mode
问题描述
今天我遇到了一个奇怪的JS错误,在try / catch块中使用 const
,我想更好地理解导致它的原因。
Today I run into a weird JS bug, working with const
inside a try/catch block, and I'd like to better understand what is causing it.
让我们看一个代码示例,值得超过千言万语:
Let's look at a code example, that is worth more than a thousand words:
try {
const FOO = 'bar';
console.log('inside:', FOO);
} catch (e) {}
console.log('outside:', FOO);
这将记录:
inside: bar
outside: bar
如果我们切换到严格模式虽然:
If we switch to "strict mode" though:
'use strict';
try {
const FOO = 'bar';
console.log('inside:', FOO);
} catch (e) {}
console.log('outside:', FOO);
现在相同的代码会产生错误:
Now the same code produces an error:
ReferenceError: FOO is not defined
如果我们更改 const
但 var
但是:
'use strict';
try {
var foo = 'bar';
console.log('inside:', foo);
} catch (e) {}
console.log('outside:', foo);
然后一切正常,即使在严格模式下:
Then it all works fine again, even in "strict mode":
inside: bar
outside: bar
任何人都可以帮助我理解为什么 const
赋值在严格模式下的try / catch块内不起作用?
Can anyone please help me understand why the const
assignment is not working inside a try/catch block in "strict mode"?
谢谢!
推荐答案
const
,如ECMAScript 6所定义,是一个块级变量声明。你得到 ReferenceError
,因为它不在之外的范围内尝试
。
const
, as defined by ECMAScript 6, is a block-level variable declaration. You get a ReferenceError
because it's not in scope outside of the try
.
然而, const / const #Firefox-specific_notesrel =nofollow noreferrer>一些引擎早在ES6之前,作为 var
的不可变对应物,具有功能级范围行为(没有TDZ)。如果您处于草率模式(您不应该这样),您可能仍会在浏览器的遗留支持中体验这一点。
However, const
was introduced in some engines long before ES6, as a immutable counterpart to var
, with function-level scope behaviour (and without TDZ). If you're in sloppy mode (which you should not be), you might still experience this as part of your browser's legacy support.
这篇关于JavaScript:使用严格模式在try / catch中定义一个常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!