ES6中const对象键的命名约定

Naming convention for const object keys in ES6

本文关键字:命名约定 对象 const ES6      更新时间:2023-09-26

es6中const对象中的键名是否有推荐的命名约定?我还没有找到一个资源来说明它们应该是大写还是小写。

const COLOR_CODES = {
  BLUE: 1,
  RED: 1
};

const COLOR_CODES = {
  blue: 1,
  red: 1
};

这篇MDN文章中的示例展示了这两种样式,所以可能两种样式都可以接受。

注意:接受的回复有一个指向过时的Google样式指南的链接

这很好(字符串字面值或整数字面值):

const PI = 3.14;
const ADDRESS = '10.0.0.1';

但是…

const myObject = { key: 'value' };
const userSuppliedNumber = getInputNumber()

Google JavaScript Style Guide说:

用const或let声明所有局部变量。使用const by默认,除非变量需要重新赋值。var关键字

每个常量都是@const静态属性或模块局部const声明,但不是所有的@const静态属性和module-localconst是常量。在选择常数情况之前,考虑是否这个领域感觉就像一个不可变的常量。例如,如果该实例的任何一个可观察状态可以改变,它几乎是当然不是常数。只是想永远不改变对象通常是不够的。

JavaScript.info说:

…大写命名的常量仅用作"硬编码"的别名。值。

根据谷歌,它将是全部大写。根据经验,大多数其他编程语言都有大写,所以我建议使用大写。

使用NAMES_LIKE_THIS作为常量

使用@const表示常量(不可重写)指针(变量或属性)。

Google javascript guidehttps://google.github.io/styleguide/javascriptguide.xml

命名规范到处都是,我个人还没有决定我的偏好,但是为了增加讨论,这是Airbnb JavaScript风格指南所说的(参见最后的例子):

// bad
const PRIVATE_VARIABLE = 'should not be unnecessarily uppercased within a file';
// bad
export const THING_TO_BE_CHANGED = 'should obviously not be uppercased';
// bad
export let REASSIGNABLE_VARIABLE = 'do not use let with uppercase variables';
// ---
// allowed but does not supply semantic value
export const apiKey = 'SOMEKEY';
// better in most cases
export const API_KEY = 'SOMEKEY';
// ---
// bad - unnecessarily uppercases key while adding no semantic value
export const MAPPING = {
  KEY: 'value'
};
// good
export const MAPPING = {
  key: 'value'
};

Google曾经推荐如下:

const COLOR_CODES = {
  BLUE: 1,
  RED: 1
};

见:https://google.github.io/styleguide/javascriptguide.xml常量

  • 对于常数使用NAMES_LIKE_THIS
  • 使用@const表示常量(不可重写)指针(变量或属性)。
  • 永远不要使用const关键字,因为它在Internet Explorer中不支持。

但是,更新后的样式指南有不同的建议。

看到goog.example.TIMEOUT_IN_MILLISECONDS = 60;在谷歌风格指南https://google.github.io/styleguide/javascriptguide.xml?showone=Constants#Constants,这似乎是像

const colorCodes = {
  BLUE: 1,
  RED: 1
};