问题描述
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...
推荐答案
这是(或不工作):
This is is just how const
works (or doesn't work):
如果你重新声明 [不同于重新分配]一个常量,Firefox [..]会抛出一个TypeError。 如果将另一个值分配给常量 [..] ,主要浏览器都不会产生任何通知或错误但是在Firefox和Chrome中重新分配(仅限)(至少从版本20开始)。
Firefox [..] throws a TypeError if you redeclare [which is different than re-assigning] a constant. None of the major browsers produce any notices or errors 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规范的一部分,并且ECM 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.
在IE 9中,使用 const a = 2
结果
In IE 9, using const a = 2
results in
在FF 14中, const a = 2; var a = 3; a = 4; a
,当评估为单个程序时,结果为
In FF 14, const a = 2; var a = 3; a = 4; a
, when evaluated as a single program, results in
与不同比在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".
在Chrome 21中, const a = 2; var a = 3; a = 4; a
的评估结果为2,没有任何警告或消息。
In Chrome 21, const a = 2; var a = 3; a = 4; a
evaluates to 2 with no warning or message.
这篇关于Javascript中的const关键字范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!