简体   繁体   English

为什么分配给const变量不会导致错误?

[英]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定义为块作用域 (当前它是函数作用域,就像varfunction )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么命名导出导致“未找到导出默认值”..错误 - Why does named export lead to “Export default was not found”..error 为什么 Javascript 引擎会忽略在初始化之前打印 const 变量的第一个错误? - Why does the Javascript engine ignore the first error which prints a const variable before it's initialized? 为什么在Dom对象中为自己分配变量会产生影响 - Why does assigning a variable to itself in a Dom Object make a difference 在JS中为变量分配函数时,为什么它会自动执行? - While assigning a function to a variable in JS, why does it gets executed automatically? 为什么将变量分配给“textContent”元素必须位于页面底部? - why does assigning a variable to 'textContent' element have to be at bottom of page? 为什么在webview上的javascript:会导致新页面? - Why does javascript: on webview lead to a new page? 为什么带有 setTimeout 的 function 不会导致堆栈溢出 - why does a function with setTimeout not lead to a stack overflow 为什么在我的const中添加两个if语句会引发错误 - Why does adding two if statements to my const throw an error 为什么在 JavaScript 中分配 Infinity 不会引发错误,但不起作用? - Why does assigning Infinity in JavaScript not throw an error, but not work? 为什么使用 HTMLObjectElement 动态生成 SVG 会导致跨域错误? - Why does dynamically generating an SVG using HTMLObjectElement lead to a Cross-Origin error?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM