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

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


当前回答

另一种选择是:

var constants = {
      MY_CONSTANT : "myconstant",
      SOMETHING_ELSE : 123
    }
  , constantMap = new function ConstantMap() {};

for(var c in constants) {
  !function(cKey) {
    Object.defineProperty(constantMap, cKey, {
      enumerable : true,
      get : function(name) { return constants[cKey]; }
    })
  }(c);
}

然后简单地:var foo = constantMap。MY_CONSTANT

如果你使用constantMap。MY_CONSTANT = "bar"它不会有任何影响,因为我们试图使用赋值操作符和getter,因此使用constantMap。MY_CONSTANT === "myconstant"仍然为真。

其他回答

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

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

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

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

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

在可能的情况下将常量分组到结构中:

例如,在我目前的游戏项目中,我使用了以下方法:

var CONST_WILD_TYPES = {
    REGULAR: 'REGULAR',
    EXPANDING: 'EXPANDING',
    STICKY: 'STICKY',
    SHIFTING: 'SHIFTING'
};

任务:

var wildType = CONST_WILD_TYPES.REGULAR;

比较:

if (wildType === CONST_WILD_TYPES.REGULAR) {
    // do something here
}

最近我用的是:

switch (wildType) {
    case CONST_WILD_TYPES.REGULAR:
        // do something here
        break;
    case CONST_WILD_TYPES.EXPANDING:
        // do something here
        break;
}

IE11是新的ES6标准,有“const”声明。 以上内容适用于IE8、IE9和IE10等早期浏览器。