[英]Why assigning to const variable does not lead to an error?
Demo: http://jsfiddle.net/rmrG9/ 演示: http : //jsfiddle.net/rmrG9/
Code: 码:
const a = 10
a = 20
alert('a: ' + a)
The output is: 输出为:
a: 10
Can you explain why the statement a = 20
did not throw an error? 您能解释为什么语句a = 20
没有引发错误吗?
Quoting the doc ( MDN ): 引用文档( MDN ):
None of the major browsers produce any notices or errors if you assign another value to a constant. 如果将另一个值分配给常量,则所有主流浏览器都不会产生任何通知或错误。 The return value of such an operation is that of the new value assigned, but the reassignment is unsuccessful only in Firefox and Chrome (at least since version 20). 此类操作的返回值是分配的新值的返回值,但是仅在Firefox和Chrome中(至少从版本20开始),重新分配才成功。
As const
is really just a proposal at the moment, browser vendors are free to implement the way they see fit. 由于const
目前实际上只是一个建议,浏览器供应商可以自由实施他们认为合适的方式。 Note that the standard will most probably define const
to be block-scoped (and currently it's function-scoped, just as var
and function
). 注意,该标准很可能会将const
定义为块作用域 (当前它是函数作用域,就像var
和function
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.