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

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


当前回答

如果值得一提的话,你可以使用$ provider .constant()在angular中定义常量

angularApp.constant('YOUR_CONSTANT', 'value');

其他回答

"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。

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>

在JavaScript中,我倾向于使用函数返回常量值。

function MY_CONSTANT() {
   return "some-value";
}


alert(MY_CONSTANT());

我在Greasemonkey脚本中使用const而不是var,但这是因为它们只会在Firefox上运行… 名称约定也确实是可行的方法(我两者都做!)

除了上面提到的,Rhino.js还实现了const。