譯者:前端小智javascript
原文:devinduct.com/blogpost/22…html
爲了保證可讀性,本文采用的音譯而非直意。前端
阿里雲最近在作活動,低至2折,有興趣能夠看看:promotion.aliyun.com/ntms/yunpar…java
若是你關注代碼自己和代碼的編寫方式,而不是隻關心它是否能工做,那麼你寫代碼是有必定的水準。專業開發人員將爲將來的本身和「其餘人」編寫代碼,而不只僅只編寫當前能工做就行的代碼。git
在此基礎上,簡潔代碼能夠定義爲自解釋的、易於人理解的、易於更改或擴展的代碼。github
如下列表一些好編寫方式,僅供參考,固然,若是你有更好的方式,歡迎留言。函數
想閱讀更多優質文章請猛戳[GitHub博客][1],一年百來篇優質文章等着你!post
用===
代替 ==
學習
// 若是處理不當,它會極大地影響程序邏輯。這就像,你想向左走,但因爲某種緣由,你向右走
0 == false // true
0 === false // false
2 == "2" // true
2 === "2" // false
// 例子
const value = "500";
if (value === 500) {
console.log(value);
// 條件不成立,不會進入
}
if (value === "500") {
console.log(value);
// 條件成立,會進入
}
複製代碼
用知名其意的方式爲變量命名,經過這種方式,當一我的看到它們時,易於搜索和理解。測試
很差的方式:
let daysSLV = 10;
let y = new Date().getFullYear();
let ok;
if (user.age > 30) {
ok = true;
}
複製代碼
好的方式:
const MAX_AGE = 30;
let daysSinceLastVisit = 10;
let currentYear = new Date().getFullYear();
...
const isUserOlderThanAllowed = user.age > MAX_AGE;
複製代碼
不要在變量名中添加額外的不須要的單詞。
很差的方式:
let nameValue;
let theProduct;
複製代碼
好的方式:
let name;
let product;
複製代碼
不要簡寫變量上下文。
很差的方式:
const users = ["John", "Marco", "Peter"];
users.forEach(u => {
doSomething();
doSomethingElse();
// ...
// ...
// ...
// ...
// 當上面代碼不少的時候 ,這 `u` 是什麼鬼
register(u);
});
複製代碼
好的方式:
const users = ["John", "Marco", "Peter"];
users.forEach(user => {
doSomething();
doSomethingElse();
// ...
// ...
// ...
// ...
register(user);
});
複製代碼
不要添加沒必要要的上下文。
很差的方式:
const user = {
userName: "John",
userSurname: "Doe",
userAge: "28"
};
...
user.userName;
複製代碼
好的方式:
const user = {
name: "John",
surname: "Doe",
age: "28"
};
...
user.name;
複製代碼
使用長而具備描述性的名稱。 考慮到函數表示某種行爲,函數名稱應該是動詞或短語,用以說明其背後的意圖以及參數的意圖。 函數的名字應該說明他們作了什麼。
很差的方式:
function notif(user) {
// implementation
}
複製代碼
好的方式:
function notifyUser(emailAddress) {
// implementation
}
複製代碼
避免使用大量參數。 理想狀況下,函數應該指定兩個或更少的參數。 參數越少,測試函數就越容易,參數多的狀況可使用對象。
很差的方式:
function getUsers(fields, fromDate, toDate) {
// implementation
}
複製代碼
好的方式:
function getUsers({ fields, fromDate, toDate }) {
// implementation
}
getUsers({
fields: ['name', 'surname', 'email'],
fromDate: '2019-01-01',
toDate: '2019-01-18'
});
複製代碼
使用默認參數替代 ||
操做
很差的方式:
function createShape(type) {
const shapeType = type || "cube";
// ...
}
複製代碼
好的方式:
function createShape(type = "cube") {
// ...
}
複製代碼
一個函數應該只作一件事,不要在一個函數中執行多個操做。
很差的方式:
function notifyUsers(users) {
users.forEach(user => {
const userRecord = database.lookup(user);
if (userRecord.isVerified()) {
notify(user);
}
});
}
複製代碼
好的方式:
function notifyVerifiedUsers(users) {
users.filter(isUserVerified).forEach(notify);
}
function isUserVerified(user) {
const userRecord = database.lookup(user);
return userRecord.isVerified();
}
複製代碼
使用Object.assign設置對象默認值。
很差的方式:
const shapeConfig = {
type: "cube",
width: 200,
height: null
};
function createShape(config) {
config.type = config.type || "cube";
config.width = config.width || 250;
config.height = config.height|| 250;
}
createShape(shapeConfig);
複製代碼
好的方式:
const shapeConfig = {
type: "cube",
width: 200
// Exclude the 'height' key
};
function createShape(config) {
config = Object.assign(
{
type: "cube",
width: 250,
height: 250
},
config
);
...
}
createShape(shapeConfig);
複製代碼
不要使用標誌做爲參數,由於它們告訴函數作的比它應該作的多。
很差的方式:
function createFile(name, isPublic) {
if (isPublic) {
fs.create(`./public/${name}`);
} else {
fs.create(name);
}
}
複製代碼
好的方式:
function createFile(name) {
fs.create(name);
}
function createPublicFile(name) {
createFile(`./public/${name}`);
}
複製代碼
不要污染全局變量。 若是須要擴展示有對象,請使用ES類和繼承,而不是在原生對象的原型鏈上建立函數。
很差的方式:
Array.prototype.myFunc = function myFunc() {
// implementation
};
複製代碼
好的方式:
class SuperArray extends Array {
myFunc() {
// implementation
}
}
複製代碼
避免使用反面條件。
很差的方式:
function isUserNotBlocked(user) {
// implementation
}
if (!isUserNotBlocked(user)) {
// implementation
}
複製代碼
好的方式:
function isUserBlocked(user) {
// implementation
}
if (isUserBlocked(user)) {
// implementation
}
複製代碼
使用條件簡寫。這可能微不足道,但值得一提。僅對布爾值使用此方法,而且若是你確信該值不會是undefined
或null
的,則使用此方法。
很差的方式:
if (isValid === true) {
// do something...
}
if (isValid === false) {
// do something...
}
複製代碼
好的方式:
if (isValid) {
// do something...
}
if (!isValid) {
// do something...
}
複製代碼
儘量避免條件句,而是使用多態性和繼承。
很差的方式:
class Car {
// ...
getMaximumSpeed() {
switch (this.type) {
case "Ford":
return this.someFactor() + this.anotherFactor();
case "Mazda":
return this.someFactor();
case "McLaren":
return this.someFactor() - this.anotherFactor();
}
}
}
複製代碼
好的方式:
class Car {
// ...
}
class Ford extends Car {
// ...
getMaximumSpeed() {
return this.someFactor() + this.anotherFactor();
}
}
class Mazda extends Car {
// ...
getMaximumSpeed() {
return this.someFactor();
}
}
class McLaren extends Car {
// ...
getMaximumSpeed() {
return this.someFactor() - this.anotherFactor();
}
}
複製代碼
class
是JavaScript中新的語法糖。一切工做就像之前的原型,只是它如今看起來不一樣,你應該更喜歡他們比ES5普通功能。
很差的方式:
const Person = function(name) {
if (!(this instanceof Person)) {
throw new Error("Instantiate Person with `new` keyword");
}
this.name = name;
};
Person.prototype.sayHello = function sayHello() { /**/ };
const Student = function(name, school) {
if (!(this instanceof Student)) {
throw new Error("Instantiate Student with `new` keyword");
}
Person.call(this, name);
this.school = school;
};
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.printSchoolName = function printSchoolName() { /**/ };
複製代碼
好的方式:
class Person {
constructor(name) {
this.name = name;
}
sayHello() {
/* ... */
}
}
class Student extends Person {
constructor(name, school) {
super(name);
this.school = school;
}
printSchoolName() {
/* ... */
}
}
複製代碼
使用連接。許多庫(如jQuery和Lodash)都使用這種模式。在類中,只需在每一個函數的末尾返回this
就能夠將更多的該類方法連接到它上。
很差的方式:
class Person {
constructor(name) {
this.name = name;
}
setSurname(surname) {
this.surname = surname;
}
setAge(age) {
this.age = age;
}
save() {
console.log(this.name, this.surname, this.age);
}
}
const person = new Person("John");
person.setSurname("Doe");
person.setAge(29);
person.save();
複製代碼
好的方式:
class Person {
constructor(name) {
this.name = name;
}
setSurname(surname) {
this.surname = surname;
// Return this for chaining
return this;
}
setAge(age) {
this.age = age;
// Return this for chaining
return this;
}
save() {
console.log(this.name, this.surname, this.age);
// Return this for chaining
return this;
}
}
const person = new Person("John")
.setSurname("Doe")
.setAge(29)
.save();
複製代碼
這只是改進代碼的一小部分。通常生活入,這裏所說的原則是人們一般不遵照的原則。他們嘗試着去作,但出於各類緣由,就沒有堅持下去。也許在項目開始時,代碼是簡潔的,可是當要在截止日期前完成時,這些原則經常被忽略,並被轉移到「TODO」或「REFACTOR」部分。在這一點上,你的客戶更但願您在最後期限以前完成任務,而不是編寫簡潔的代碼。
爲了回饋讀者,《大遷世界》不按期舉行(每月一到三次),現金抽獎活動,保底200,外加用戶讚揚,但願你能成爲大遷世界的小錦鯉,快來試試吧
乾貨系列文章彙總以下,以爲不錯點個Star,歡迎 加羣 互相學習。
我是小智,公衆號「大遷世界」做者,對前端技術保持學習愛好者。我會常常分享本身所學所看的乾貨,在進階的路上,共勉!
關注公衆號,後臺回覆福利,便可看到福利,你懂的。
每次整理文章,通常都到2點才睡覺,一週4次左右,挺苦的,還望支持,給點鼓勵