Are there constants in JavaScript?

后端 未结 30 2879
抹茶落季
抹茶落季 2020-11-22 08:53

Is there a way to use constants in JavaScript?

If not, what\'s the common practice for specifying variables that are used as constants?

30条回答
  •  悲&欢浪女
    2020-11-22 09:40

    Another alternative is something like:

    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);
    }
    

    Then simply: var foo = constantMap.MY_CONSTANT

    If you were to constantMap.MY_CONSTANT = "bar" it would have no effect as we're trying to use an assignment operator with a getter, hence constantMap.MY_CONSTANT === "myconstant" would remain true.

提交回复
热议问题