Javascript ENUM 模式命名约定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13233137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:09:12  来源:igfitidea点击:

Javascript ENUM pattern naming convention

javascriptnaming-conventionsjshint

提问by Benjamin Gruenbaum

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

我正在开发一个 javascript 项目,它需要使用 javascript“枚举”,意思是像这样的对象:

var WinnerEnum = {
            Player1: 1,
            Player2: 2,
            Draw: 0
    };

This is working great for me, however, I have no idea what is the proper way (according to convention) to name the Enum because as far as I know only class names start with a capital letter (indicating the ability to call a constructor on).

这对我来说很有用,但是,我不知道命名 Enum 的正确方法是什么(根据约定),因为据我所知,只有类名以大写字母开头(表示能够调用构造函数) )。

JSHint also outputs the following warning:

JSHint 还输出以下警告:

Missing 'new' prefix when invoking a constructor.

If there is no convention, I would appreciate a good way to name enums that would not confuse them with class names. Update 2014: JSHint no longer does this.

如果没有约定,我会很欣赏一种命名枚举的好方法,它不会将它们与类名混淆。2014 年更新:JSHint 不再这样做。

采纳答案by Benjamin Gruenbaum

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

根据 Google 的编码约定,这确实是在 javascript 中命名枚举的正确方法。

As requested here is a link.

根据要求,这里有一个链接

回答by dharcourt

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

这确实是命名枚举的正确方法,但枚举值应该是 ALL_CAPS 而不是 UpperCamelCase,如下所示:

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

This is similar to Java's naming conventionfor enums.

这类似于Java 的枚举命名约定

Some references:

一些参考:

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.

我找不到任何比 Google 的样式指南和上述著作更权威的参考文献,这些著作是由认真考虑过枚举的人撰写的,但我很想听听任何更好的参考文献。