Skip to content

一、使用有意义并且可读的变量名称

不好的:

js
const yyyymmdstr = moment().format('YYYY/MM/DD');

好的:

js
const currentDate = moment().format('YYYY/MM/DD');

二、为相同类型的变量使用相同的词汇

不好的:

js
getUserInfo();
getClientData();
getCustomerRecord();

好的:

js
getUser();

三、使用可搜索的名称

不好的:

js
// 艹, 86400000 是什么鬼?
setTimeout(blastOff, 86400000);

好的:

js
// 将它们声明为全局常量 `const` 。
const MILLISECONDS_IN_A_DAY = 86400000;

setTimeout(blastOff, MILLISECONDS_IN_A_DAY);

通常:项目里面会有很多字典、或者自定义的标识。如果出现频率挺多,尽量新建constant文件,统一管理。而且做好变量提示内容。例如:

js
/**
 * @description 招标类型
 */
 export const TENDER_TYPE = {
  /**
   * @description 邀请招标
  */
  INVITE_TENDER: 10201001,
  /**
   * @description 公开招标
  */
  PUBLIC_TENDER: 10201002,
  /**
   * @description 非招标
  */
  NOT_TENDER: 10201003,
}

这样之后,我们在其他页面使用它的时候,鼠标放上去就自动提示它的含义啦。如果用了ts,那配合着更好不过了。

四、避免心理映射

显示比隐式更好

不好的:

js
const locations = ['Austin', 'New York', 'San Francisco'];
locations.forEach((l) => {
  doStuff();
  doSomeOtherStuff();
  // ...
  // ...
  // ...
  // 等等, `l` 是啥?
  dispatch(l);
});

好的:

js
const locations = ['Austin', 'New York', 'San Francisco'];
locations.forEach((location) => {
  doStuff();
  doSomeOtherStuff();
  // ...
  // ...
  // ...
  dispatch(location);
});

五、不添加不必要的上下文

如果你的类名/对象名有意义, 不要在变量名上再重复。

不好的:

js
const Car = {
  carMake: 'Honda',
  carModel: 'Accord',
  carColor: 'Blue'
};

function paintCar(car) {
  car.carColor = 'Red';
}

好的:

js
const Car = {
  make: 'Honda',
  model: 'Accord',
  color: 'Blue'
};

function paintCar(car) {
  car.color = 'Red';
}

六、使用默认变量替代短路运算或条件

如果你的类名/对象名有意义, 不要在变量名上再重复。

不好的:

js
function createMicrobrewery(name) {
  const breweryName = name || 'Hipster Brew Co.';
  // ...
}

好的:

js
function createMicrobrewery(breweryName = 'Hipster Brew Co.') {
  // ...
}

七、使用解释性的变量

不好的:

js
const address = 'One Infinite Loop, Cupertino 95014';
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
saveCityZipCode(address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2]);

好的:

js
const address = 'One Infinite Loop, Cupertino 95014';
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
const [, city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);

可能有的伙伴对这个有点疑惑,使用解释性的变量的意思是什么呢,你看不好的代码saveCityZipCode的传参,感觉很难看懂对吧,但是你看好的代码时候就知道saveCityZipCode就是保存city和zipCode。