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

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


当前回答

声明一个只读命名的常量。 通过const声明的变量不能被重新声明或重新赋值。 常量可以用大写或小写来声明,但通用的 惯例是全部使用大写字母。

// const c;
// c = 9;   //intialization and declearation at same place
const c = 9;
// const c = 9;// re-declare and initialization is not possible
console.log(c);//9

其他回答

声明一个只读命名的常量。 通过const声明的变量不能被重新声明或重新赋值。 常量可以用大写或小写来声明,但通用的 惯例是全部使用大写字母。

// const c;
// c = 9;   //intialization and declearation at same place
const c = 9;
// const c = 9;// re-declare and initialization is not possible
console.log(c);//9

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

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

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;

不,不一般。Firefox实现了const,但我知道IE没有。


@John指出了const的一个常用命名实践,在其他语言中已经使用了很多年,我看不出为什么你不能使用它。当然,这并不意味着有人不会重写变量的值。:)

在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”属性保留了其原始价值。你已经为自己设置了一些不错的“绿色”临时常数……

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

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