Javascript 中的 const 关键字作用域

2022-01-23 00:00:00 constants javascript
1. >>> const a = 2
2. >>> var a = 3
3. >>> a = 4
4. >>> a // print 2

为什么允许运行3号线?const 似乎比没有任何关键字更全局"...

Why the operation line 3 is allowed? const seems more "global" than without any keyword...

推荐答案

这是 就是 const 的工作原理(或不起作用):

This is is just how const works (or doesn't work):

创建一个常量1,对于声明它的函数来说,它可以是全局的或局部的.常量遵循与变量相同的范围规则 [.. 并且不能与同一范围内的函数或变量共享名称].

Creates a constant1 that can be global or local to the function in which it is declared. Constants follow the same scope rules as variables [.. and cannot share a name] with a function or a variable in the same scope.

如果您重新声明2 [与重新分配不同] 常量,则

Firefox [..] 会引发 TypeError.如果您分配另一个值给常量 [..] ,所有主要浏览器都不会产生任何通知或错误2,3重新分配不成功(仅)在 Firefox 和 Chrome 中(至少从版本 20 开始).

Firefox [..] throws a TypeError if you redeclare2 [which is different than re-assigning] a constant. None of the major browsers produce any notices or errors2,3 if you assign another value to a constant [..] but the reassignment is unsuccessful (only) in Firefox and Chrome (at least since version 20).

请注意,const 不是 ECMAScript 5 规范的一部分,JavaScript 1.5 语义将在 ECMAScript 6 中重新定义.

Note that const is not part of the ECMAScript 5 specification and the JavaScript 1.5 semantics will be re-defined in ECMAScript 6.

行为将在支持和重新声明/重新分配语义方面因浏览器实现而异.

Behavior will vary across browser implementations with respect to support and re-declaration/re-assignments semantics.

1 在 IE 9 中,使用 const a = 2 会导致

1 In IE 9, using const a = 2 results in

语法错误"

2 在 FF 14 中,const a = 2;变量 a = 3;a = 4;a,当作为单个程序评估时,会导致

2 In FF 14, const a = 2; var a = 3; a = 4; a, when evaluated as a single program, results in

TypeError: 重新声明 const a

TypeError: redeclaration of const a

这与在 REPL 中一次执行每一行 不同.我怀疑这是因为var被提升在const之上,并且因为const不能与同一范围内的函数或变量".

which is different than executing each line one-at-a-time in the REPL. I suspect this is because var is hoisted above the const and because a const "cannot share a name with a function or variable in the same scope".

3 在 Chrome 21 中,const a = 2;变量 a = 3;a = 4;a 计算结果为 2,没有警告或消息.

3 In Chrome 21, const a = 2; var a = 3; a = 4; a evaluates to 2 with no warning or message.

相关文章