在JavaScript中有使用常量的方法吗?

如果不是,指定用作常量的变量的常见做法是什么?


当前回答

"use strict";

var constants = Object.freeze({
    "π": 3.141592653589793 ,
    "e": 2.718281828459045 ,
    "i": Math.sqrt(-1)
});

constants.π;        // -> 3.141592653589793
constants.π = 3;    // -> TypeError: Cannot assign to read only property 'π' …
constants.π;        // -> 3.141592653589793

delete constants.π; // -> TypeError: Unable to delete property.
constants.π;        // -> 3.141592653589793

看到Object.freeze。如果想让常量引用只读,也可以使用const。

其他回答

另一种选择是:

var constants = {
      MY_CONSTANT : "myconstant",
      SOMETHING_ELSE : 123
    }
  , constantMap = new function ConstantMap() {};

for(var c in constants) {
  !function(cKey) {
    Object.defineProperty(constantMap, cKey, {
      enumerable : true,
      get : function(name) { return constants[cKey]; }
    })
  }(c);
}

然后简单地:var foo = constantMap。MY_CONSTANT

如果你使用constantMap。MY_CONSTANT = "bar"它不会有任何影响,因为我们试图使用赋值操作符和getter,因此使用constantMap。MY_CONSTANT === "myconstant"仍然为真。

IE确实支持常量,比如:

<script language="VBScript">
 Const IE_CONST = True
</script>
<script type="text/javascript">
 if (typeof TEST_CONST == 'undefined') {
    const IE_CONST = false;
 }
 alert(IE_CONST);
</script>

关键字“const”早前就被提出了,现在它已经被正式包含在ES6中。通过使用const关键字,可以传递一个作为不可变字符串的值/字符串。

忘记IE,使用const关键字。

const关键字在javscript语言中可用,但不支持IE浏览器。其余所有浏览器支持。