JavaScript: define a constant inside try / catch with strict mode

走远了吗. 提交于 2019-12-09 16:06:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!