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

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


当前回答

在JavaScript中引入常量充其量是一种hack。

在JavaScript中创建持久且全局可访问的值的一个好方法是声明一个具有“只读”属性的对象文字,如下所示:

            my={get constant1(){return "constant 1"},
                get constant2(){return "constant 2"},
                get constant3(){return "constant 3"},
                get constantN(){return "constant N"}
                }

你可以将你所有的常量组合在一个单独的“my”附属对象中,在那里你可以查找你存储的值或其他任何你决定放在那里的东西。现在让我们来测试一下它是否有效:

           my.constant1; >> "constant 1" 
           my.constant1 = "new constant 1";
           my.constant1; >> "constant 1" 

正如我们所看到的,“我的”。Constant1”属性保留了其原始价值。你已经为自己设置了一些不错的“绿色”临时常数……

当然,这只能防止您意外地修改、修改、无效或清空您的属性常量值,就像在给定的例子中那样。

否则我仍然认为常数是傻瓜用的。 我仍然认为,用你巨大的自由换取一个小小的欺骗性的安全是最糟糕的交易。

其他回答

从ES2015开始,JavaScript有了const的概念:

const MY_CONSTANT = "some-value";

这将工作在几乎所有的浏览器除了ie8, 9和10。有些可能还需要启用严格模式。

如果你需要支持旧的浏览器或使用遗留代码,你可以使用var和像ALL_CAPS这样的约定来表明某些值不应该被修改:

var MY_CONSTANT = "some-value";

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

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

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

您是否试图保护变量不被修改?如果是,那么你可以使用模块模式:

var CONFIG = (function() {
     var private = {
         'MY_CONST': '1',
         'ANOTHER_CONST': '2'
     };

     return {
        get: function(name) { return private[name]; }
    };
})();

alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.MY_CONST = '2';
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.private.MY_CONST = '2';                 // error
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

使用这种方法,不能修改值。但是,你必须在CONFIG:(上使用get()方法。

如果您不需要严格保护变量值,那么只需按照建议执行并使用ALL CAPS约定即可。