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

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


当前回答

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

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

其他回答

有一段时间,我在传递给with()语句的对象字面量中指定了“常量”(实际上仍然不是常量)。我觉得这很聪明。这里有一个例子:

with ({
    MY_CONST : 'some really important value'
}) {
    alert(MY_CONST);
}

在过去,我还创建了一个CONST名称空间,将所有常量放在其中。还有开销。天哪。

现在,我写var MY_CONST = 'whatever';吻。

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。

Mozillas MDN Web Docs包含了关于const的很好的例子和解释。摘录:

// define MY_FAV as a constant and give it the value 7
const MY_FAV = 7;

// this will throw an error - Uncaught TypeError: Assignment to constant variable.
MY_FAV = 20;

但遗憾的是,IE9/10仍然不支持const。荒谬的原因是:

IE9用const做什么?所以 到目前为止,我们的决定是不去 支持它。这还不是一个共识 功能,因为它从来没有可用 在所有浏览器上。 ... 最后,这似乎是最好的 网络的长期解决方案是 把它放在外面等着 标准化流程来运行它们 课程。

他们没有实现它是因为其他浏览器没有正确地实现它?!太害怕做得更好?标准定义与否,常量就是常量:设置一次,永不改变。

所有的想法:每个函数都可以被重写(XSS等)。所以var和function(){return}没有区别。Const是唯一真正的常量。

更新: IE11支持const:

IE11支持新兴的ECMAScript 6标准中定义良好且常用的特性,包括let、const、Map、Set和WeakMap,以及__proto__,以改进互操作性。

然而,没有确切的跨浏览器预定义的方法来做到这一点,你可以通过控制变量的范围来实现,如其他答案所示。

但是我建议使用名称空间来区别于其他变量。这将使与其他变量的碰撞概率降到最低。

正确的命名空间

var iw_constant={
     name:'sudhanshu',
     age:'23'
     //all varibale come like this
}

使用时,它会是iw_constant。name或iw_constant。age

你也可以使用Object.freeze方法阻止添加任何新键或改变iw_constant中的任何键。但是它不支持传统浏览器。

ex:

Object.freeze(iw_constant);

对于较老的浏览器,可以使用polyfill进行冻结方法。


如果你可以调用函数下面是最好的跨浏览器方式定义常量。将对象限定在一个自执行函数中,并为常量返回一个get函数 例:

var iw_constant= (function(){
       var allConstant={
             name:'sudhanshu',
             age:'23'
             //all varibale come like this

       };

       return function(key){
          allConstant[key];
       }
    };

//获取值use Iw_constant ('name')或Iw_constant ('age')


**在这两个例子中,你必须非常注意名称间距,这样你的对象或函数不会被其他库替换。(如果对象或函数本身将被替换,则整个常量将消失)