整洁的代码不仅仅是让人看起来舒服,更重要的是遵循一些规范能够让你的代码更容易维护,同时降低bug几率。
小编创建了一个群,有前端系统的学习资料和帮助解答问题,欢迎各位小白和大牛们的加入,点击:加群
- 用命名的变量代替数组下标
// bad
const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
saveCityZipCode(
// 下标1,2不易于理解
address.match(cityZipCodeRegex)[1],
address.match(cityZipCodeRegex)[2]
);
// good
const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
// 使用数组解构更好的命名变量
const [, city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);
- 函数的参数最好 <= 2个,尽量避免3个。
如果有很多参数就利用 object 传递,并使用解构。
注意 object array 这些引用类型的值是 mutable 的。
-
一个函数只做一件事。
好处在于 compose, test, and reason about 。 -
不要自行扩展原型
如果想扩展原型,可以先继承再添加方法,防止污染。
// bad
Array.prototype.diff = function diff(comparisonArray) {
const hash = new Set(comparisonArray);
return this.filter(elem => !hash.has(elem));
};
// good
class SuperArray extends Array {
diff(comparisonArray) {
const hash = new Set(comparisonArray);
return this.filter(elem => !hash.has(elem));
}
}
- 用多态来代替条件语句
// bad
if (type === 'text') {
// do something
} else if (type === 'select') {
// do something else
}
我个人写这种代码的一种常用方式是:
const control = {
text: {
mapper() {},
restore(){},
name: 'this is a text field',
},
select: {
mapper() {},
restore(){},
name: 'this is a select field',
}
}
control[type].mapper();
实际上就是多态(polymorphism),也可以考虑用 class 的方式,大概这样:
class Field {
...
}
class TextField extends Field {
mapper(){}
restore(){}
name = 'this is a text field';
}
class SelectField extends Field {
mapper(){}
restore(){}
name = 'this is a select field';
}
- 使用 getter 和 setter 函数。
// bad
function makeBankAccount() {
// ...
return {
balance: 0
// ...
};
}
const account = makeBankAccount();
account.balance = 100;
// good
function makeBankAccount() {
// this one is private
let balance = 0;
// a "getter", made public via the returned object below
function getBalance() {
return balance;
}
// a "setter", made public via the returned object below
function setBalance(amount) {
// ... validate before updating the balance
balance = amount;
}
return {
// ...
getBalance,
setBalance
};
}
const account = makeBankAccount();
account.setBalance(100);