Are there constants in JavaScript?

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

    Group constants into structures where possible:

    Example, in my current game project, I have used below:

    var CONST_WILD_TYPES = {
        REGULAR: 'REGULAR',
        EXPANDING: 'EXPANDING',
        STICKY: 'STICKY',
        SHIFTING: 'SHIFTING'
    };
    

    Assignment:

    var wildType = CONST_WILD_TYPES.REGULAR;
    

    Comparision:

    if (wildType === CONST_WILD_TYPES.REGULAR) {
        // do something here
    }
    

    More recently I am using, for comparision:

    switch (wildType) {
        case CONST_WILD_TYPES.REGULAR:
            // do something here
            break;
        case CONST_WILD_TYPES.EXPANDING:
            // do something here
            break;
    }
    

    IE11 is with new ES6 standard that has 'const' declaration.
    Above works in earlier browsers like IE8, IE9 & IE10.

提交回复
热议问题