Are there constants in JavaScript?

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

    An improved version of Burke's answer that lets you do CONFIG.MY_CONST instead of CONFIG.get('MY_CONST').

    It requires IE9+ or a real web browser.

    var CONFIG = (function() {
        var constants = {
            'MY_CONST': 1,
            'ANOTHER_CONST': 2
        };
    
        var result = {};
        for (var n in constants)
            if (constants.hasOwnProperty(n))
                Object.defineProperty(result, n, { value: constants[n] });
    
        return result;
    }());
    

    * The properties are read-only, only if the initial values are immutable.

提交回复
热议问题