如何让js更加优雅,如何提高代码的可读性、复用性、扩展性,可以从以下几点讨论。
-
变量
-
函数
-
类
-
异步
一、变量:
1、用有意义且常用的单词命名
// Bad:
const yyyymmdstr = moment().format('YYYY/MM/DD');
// Good:
const currentDate = moment().format('YYYY/MM/DD');
2、避免无意义的前缀
// Bad:
const car = {
carMake: 'Honda',
carModel: 'Accord'
};
function paintCar( car ) {
car.carColor = 'Red';
}
// Good:
const car = {
make: 'Honda',
model: 'Accord'
};
function paintCar( car ) {
car.color = 'Red';
}
3、传参使用默认值
// Bad:
function createMicrobrewery( name ) {
const breweryName = name || 'Hipster Brew Co.';
// ...
}
// Good:
function createMicrobrewery( name = 'Hipster Brew Co.' ) {
// ...
}
5、避免 == 的使用
//(1)如果你确定了变量的类型,那么就没必要使用==了
//(2)如果类型不确定,那么应该手动做一下类型转换
var totalPage = "5";
if(parseInt(totalPage) === 1){
}
4、按强类型风格写代码
// (1)定义变量的时候要指明类型
var num = 0,
str = '',
obj = null;// 定义变量的时候就给他一个默认值,这样不仅方便了解释器,也方便了阅读代码的人,他会在心里有数——知道这些变量可能会当作什么用。
// (2)不要随意地改变变量的类型
// (3)函数的返回类型应该是要确定的
function getPrice(count){
if(count < 0) return-1;
elsereturn count * 100;
}
二、函数
1、函数名上体现它的作用
// Bad:
function addToDate( date, month ) {
// ...
}
const date = new Date();
addToDate( date, 1 );
// Good:
function addMonthToDate( month, date ) {
// ...
}
const date = new Date();
addMonthToDate( 1, date );
2、使用 Object.assign 设置默认属性
// Bad:
const menuConfig = {
title: null,
body: 'Bar'
};
function createMenu(config) {
config.title = config.title || 'Foo';
config.body = config.body || 'Bar';
}
createMenu(menuConfig);
// Good:
const menuConfig = {
title: 'Order',
body: 'Send'
};
function createMenu(config) {
config = Object.assign({
title: 'Foo',
body: 'Bar'
}, config);
// config : {title: "Order", body: "Bar"}
// ...
}
createMenu(menuConfig);
3、用return退出多重循环:假设在函数体内有一个两重循环语句,我们需要在内层循环中判断,当达到某个临界条件时退出外层的循环。
var print = function( i ){
console.log( i );
};
var func = function(){
for ( var i = 0; i < 10; i++ ){
for ( var j = 0; j < 10; j++ ){
if ( i * j >30 ){
return print( i );
}
}
}
};
func();
4、尽量别用“非”条件句
// Bad:
function isDOMNodeNotPresent(node) {
// ...
}
if (!isDOMNodeNotPresent(node)) {
// ...
}
// Good:
function isDOMNodePresent(node) {
// ...
}
if (isDOMNodePresent(node)) {
// ...
}

5、删除重复代码,合并相似函数;删除弃用代码
// bad
var paging = function( currPage ){
if ( currPage <= 0 ){
currPage = 0;
jump( currPage ); // 跳转
}else if ( currPage >= totalPage ){
currPage = totalPage;
jump( currPage ); // 跳转
}else{
jump( currPage ); // 跳转
}
};
// good
var paging = function( currPage ){
if ( currPage <= 0 ){
currPage = 0;
}else if ( currPage >= totalPage ){
currPage = totalPage;
}
jump( currPage ); // 把jump函数独立出来
};
2、函数参数( 最好 2 个或更少 ),如果参数超过两个,建议使用 ES6 的解构语法,不用考虑参数的顺序。
3、一个方法只做一件事情
三、类
1、使用 ES6 的 class:用 class 可以减少代码量,class 还可以很方便地实现继承、静态的成员函数,就不需要自己再去通过一些技巧去实现了。
// bad
function Person(name, age){
this.name = name;
this.age = age;
}
Person.prototype.addAge = function(){
this.age++;
};
Person.prototype.setName = function(name){
this.name = name;
};
// good
class Person{
constructor(name, age){
this.name = name;
this.age = age;
}
addAge(){
this.age++;
}
setName(name){
this.name = name;
}
}

2、使用链式调用
四、异步
使用 promise 或者 Async/Await 代替回调
// 获取数据
async getData(params) {
const p0 = func getName({})
const p1 = func getAge({})
const res = await Promise.all([p0, p1])
const d0 = res[0]
const d1 = res[1]
},

注:想了解更多,可查看以下原文。