Javascript ENUM pattern naming convention

前端 未结 2 957
北荒
北荒 2021-02-07 01:18

I am working on a javascript project which requires use of javascript \"Enums\" meaning Objects like:

var WinnerEnum = {
            Player1: 1,
            Play         


        
相关标签:
2条回答
  • 2021-02-07 01:42

    According to Google's coding conventions this is the correct way indeed to name an enum in javascript.

    As requested here is a link.

    0 讨论(0)
  • 2021-02-07 01:58

    That is indeed the correct way to name the enum, but the enum values should be ALL_CAPS instead of UpperCamelCase, like this:

    var WinnerEnum = {
        PLAYER_1: 1,
        PLAYER_2: 2,
        DRAW: 0
    };
    

    This is similar to Java's naming convention for enums.

    Some references:

    • Google JavaScript Style Guide
    • Stijn de Witt's Blog
    • Enumify documentation

    As with coding style in general, you'll find people doing things in many different ways, with each way having its own set of good reason. To make things easiest for anyone reading and working with your code, however, I would recommend using the style which has the most authoritative reference and therefore usually the most widespread adoption.

    I couldn't find any reference more authoritative than Google's style guide and the writings above, written by people who have given some serious thought to enums, but I'd be interested to hear of any better references.

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