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

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


当前回答

const关键字在ECMAScript 6草案中,但到目前为止它只获得了少量的浏览器支持:http://kangax.github.io/compat-table/es6/。语法为:

const CONSTANT_NAME = 0;

其他回答

我的观点(只适用于对象)。

var constants = (function(){
  var a = 9;

  //GLOBAL CONSTANT (through "return")
  window.__defineGetter__("GCONST", function(){
    return a;
  });

  //LOCAL CONSTANT
  return {
    get CONST(){
      return a;
    }
  }
})();

constants.CONST = 8; //9
alert(constants.CONST); //9

试试!但是要明白,这是对象,而不是简单的变量。

还可以试试:

const a = 9;

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

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

正确的命名空间

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')


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

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

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

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>