Are there constants in JavaScript?

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

提交回复
热议问题