The const keyword in JavaScript:
今天(2014年)是否建议使用const关键字在javascript中声明常量?是否仍存在浏览器兼容性问题?还有,有没有一种方法可以声明一个全局常量?
注意:这个问题不是重复的,我问的是2014年。堆栈溢出中的其他日志可追溯到2008-2012年
截至2014年6月,MDN表示:
The current implementation of const is a Mozilla-specific extension
and is not part of ECMAScript 5. It is supported in Firefox & Chrome
(V8). As of Safari 5.1.7 and Opera 12.00, if you define a variable
with const in these browsers, you can still change its value later. It
is not supported in Internet Explorer 6-10, but is included in
Internet Explorer 11. The const keyword currently declares the
constant in the function scope (like variables declared with var).Firefox, at least since version 13, throws a TypeError if you
redeclare a constant. 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).const is going to be defined by ECMAScript 6, but with different
semantics. Similar to variables declared with the let statement,
constants declared with const will be block-scoped.
这里参考
然而,ES6草案引入了不同的
所以基本上:
- 一些浏览器实现了旧的非标准方式。
- 其他浏览器允许使用
const 声明的变量在以后更改其值。 - 其他浏览器根本不实现它。
- 目前没有浏览器(Afaik)实现ES6方式。
参见MDN文章。