问题
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);
This will log:
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
If we change const
with var
though:
'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
Can anyone please help me understand why the const
assignment is not working inside a try/catch block in "strict mode"?
Thanks!
回答1:
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
.
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.
回答2:
Your JavaScript runtime has a partial implementation of ES6 const.
ReferenceError
is the expected behaviour for your first example, because const is block scoped and you access FOO
outside the defining try
block.
The engine you are using supports the const
syntax, but it only applies block scoping semantics in strict mode.
The current stable Chrome (46) does this. Chrome 48, however, applies block scope with or without strict mode.
var
is not block scoped, so your last example works as expected.
来源:https://stackoverflow.com/questions/33457167/javascript-define-a-constant-inside-try-catch-with-strict-mode