Javascript中的const关键字范围 [英] const keyword scope in Javascript

查看:484
本文介绍了Javascript中的const关键字范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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规范的一部分,并且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.

1 在IE 9中,使用 const a = 2 结果

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


语法错误

"Syntax error"

2 在FF 14中, const a = 2; var 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; var 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.

这篇关于Javascript中的const关键字范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆