Are there constants in JavaScript?

后端 未结 30 2569
抹茶落季
抹茶落季 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

    Clearly this shows the need for a standardized cross-browser const keyword.

    But for now:

    var myconst = value;
    

    or

    Object['myconst'] = value;
    

    Both seem sufficient and anything else is like shooting a fly with a bazooka.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 09:40

    in Javascript already exists constants. You define a constant like this:

    const name1 = value;
    

    This cannot change through reassignment.

    0 讨论(0)
  • 2020-11-22 09:41
    "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
    

    See Object.freeze. You can use const if you want to make the constants reference read-only as well.

    0 讨论(0)
  • 2020-11-22 09:41

    If you don't mind using functions:

    var constant = function(val) {
       return function() {
            return val;
        }
    }
    

    This approach gives you functions instead of regular variables, but it guarantees* that no one can alter the value once it's set.

    a = constant(10);
    
    a(); // 10
    
    b = constant(20);
    
    b(); // 20
    

    I personally find this rather pleasant, specially after having gotten used to this pattern from knockout observables.

    *Unless someone redefined the function constant before you called it

    0 讨论(0)
  • 2020-11-22 09:42

    Are you trying to protect the variables against modification? If so, then you can use a module pattern:

    var CONFIG = (function() {
         var private = {
             'MY_CONST': '1',
             'ANOTHER_CONST': '2'
         };
    
         return {
            get: function(name) { return private[name]; }
        };
    })();
    
    alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1
    
    CONFIG.MY_CONST = '2';
    alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1
    
    CONFIG.private.MY_CONST = '2';                 // error
    alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1
    

    Using this approach, the values cannot be modified. But, you have to use the get() method on CONFIG :(.

    If you don't need to strictly protect the variables value, then just do as suggested and use a convention of ALL CAPS.

    0 讨论(0)
提交回复
热议问题