Are there constants in JavaScript?

2018-12-31 13:46发布

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条回答
何处买醉
2楼-- · 2018-12-31 14:23

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

查看更多
不流泪的眼
3楼-- · 2018-12-31 14:25

Yet there is no exact cross browser predefined way to do it , you can achieve it by controlling the scope of variables as showed on other answers.

But i will suggest to use name space to distinguish from other variables. this will reduce the chance of collision to minimum from other variables.

Proper namespacing like

var iw_constant={
     name:'sudhanshu',
     age:'23'
     //all varibale come like this
}

so while using it will be iw_constant.name or iw_constant.age

You can also block adding any new key or changing any key inside iw_constant using Object.freeze method. However its not supported on legacy browser.

ex:

Object.freeze(iw_constant);

For older browser you can use polyfill for freeze method.


If you are ok with calling function following is best cross browser way to define constant. Scoping your object within a self executing function and returning a get function for your constants ex:

var iw_constant= (function(){
       var allConstant={
             name:'sudhanshu',
             age:'23'
             //all varibale come like this

       };

       return function(key){
          allConstant[key];
       }
    };

//to get the value use iw_constant('name') or iw_constant('age')


** In both example you have to be very careful on name spacing so that your object or function shouldn't be replaced through other library.(If object or function itself wil be replaced your whole constant will go)

查看更多
冷夜・残月
4楼-- · 2018-12-31 14:26

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.

查看更多
零度萤火
5楼-- · 2018-12-31 14:27

The const keyword is in the ECMAScript 6 draft but it thus far only enjoys a smattering of browser support: http://kangax.github.io/compat-table/es6/. The syntax is:

const CONSTANT_NAME = 0;
查看更多
姐姐魅力值爆表
6楼-- · 2018-12-31 14:28

Since ES2015, JavaScript has a notion of const:

const MY_CONSTANT = "some-value";

This will work in pretty much all browsers except IE 8, 9 and 10. Some may also need strict mode enabled.

You can use var with conventions like ALL_CAPS to show that certain values should not be modified if you need to support older browsers or are working with legacy code:

var MY_CONSTANT = "some-value";
查看更多
深知你不懂我心
7楼-- · 2018-12-31 14:28

No, not in general. Firefox implements const but I know IE doesn't.


@John points to a common naming practice for consts that has been used for years in other languages, I see no reason why you couldn't use that. Of course that doesn't mean someone will not write over the variable's value anyway. :)

查看更多
登录 后发表回答