JavaScript代碼優(yōu)雅,簡潔的編寫技巧總結
1. 強類型檢查
用===代替 ==
// 如果處理不當,它會極大地影響程序邏輯。這就像,你想向左走,但由于某種原因,你向右走 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);
// 條件成立,會進入
}2.變量
用知名其意的方式為變量命名,通過這種方式,當一個人看到它們時,易于搜索和理解。
不好的方式:
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;3. 函數(shù)
使用長而具有描述性的名稱。 考慮到函數(shù)表示某種行為,函數(shù)名稱應該是動詞或短??語,用以說明其背后的意圖以及參數(shù)的意圖。 函數(shù)的名字應該說明他們做了什么。
不好的方式:
function notif(user) {
// implementation
}
好的方式:
function notifyUser(emailAddress) {
// implementation
}避免使用大量參數(shù)。 理想情況下,函數(shù)應該指定兩個或更少的參數(shù)。 參數(shù)越少,測試函數(shù)就越容易,參數(shù)多的情況可以使用對象。
不好的方式:
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'
});使用默認參數(shù)替代 || 操作
不好的方式:
function createShape(type) {
const shapeType = type || "cube";
// ...
}
好的方式:
function createShape(type = "cube") {
// ...
}一個函數(shù)應該只做一件事,不要在一個函數(shù)中執(zhí)行多個操作。
不好的方式:
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);不要使用標志作為參數(shù),因為它們告訴函數(shù)做的比它應該做的多。
不好的方式:
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}`);
}不要污染全局變量。 如果需要擴展現(xiàn)有對象,請使用ES類和繼承,而不是在原生對象的原型鏈上創(chuàng)建函數(shù)。
不好的方式:
Array.prototype.myFunc = function myFunc() {
// implementation
};
好的方式:
class SuperArray extends Array {
myFunc() {
// implementation
}
}4. 條件
避免使用反面條件。
不好的方式:
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...
}盡可能避免條件句,而是使用多態(tài)性和繼承。
不好的方式:
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();
}
}5. 類
class 是JavaScript中新的語法糖。一切工作就像以前的原型,只是它現(xiàn)在看起來不同,你應該更喜歡他們比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)都使用這種模式。在類中,只需在每個函數(shù)的末尾返回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();總結
這只是改進代碼的一小部分。一般生活入,這里所說的原則是人們通常不遵守的原則。他們嘗試著去做,但出于各種原因,就沒有堅持下去。也許在項目開始時,代碼是簡潔的,但是當要在截止日期前完成時,這些原則常常被忽略,并被轉(zhuǎn)移到“TODO”或“REFACTOR”部分。在這一點上,你的客戶更希望您在最后期限之前完成任務,而不是編寫簡潔的代碼。
更多關于如何優(yōu)雅,簡潔的編寫JavaScript代碼技巧請查看下面的相關文章
相關文章
JavaScript中使用指數(shù)方法Math.exp()的簡介
這篇文章主要介紹了JavaScript中使用指數(shù)方法Math.exp(),是JS入門學習中的基礎知識,需要的朋友可以參考下2015-06-06
JavaScript高級程序設計(第3版)學習筆記9 js函數(shù)(下)
函數(shù)是一種對象,擁有一般對象具有的所有特征,除了函數(shù)可以有自己的屬性和方法外,還可以做為一個引用類型的值去使用,實際上我們前面的例子中已經(jīng)有過將函數(shù)作為一個對象屬性的值,又比如函數(shù)也可以作為另一個函數(shù)的參數(shù)或者返回值,異步處理中的回調(diào)函數(shù)就是一個典型的用法2012-10-10
一個簡單的網(wǎng)站訪問JS計數(shù)器 刷新1次加1次訪問
一個簡單的網(wǎng)站訪問JS計數(shù)器,一般就是學習下原來,不建議使用,現(xiàn)在cnzz或百度統(tǒng)計多試不錯的2012-09-09
js的參數(shù)有長度限制嗎?發(fā)現(xiàn)不能超過2083個字符
用substring大致對入口參數(shù)的值處理了一下,發(fā)現(xiàn)不能超過2083個字符。難道js的函數(shù)參數(shù)有長度限制2014-04-04
JavaScript 基礎篇之對象、數(shù)組使用介紹(三)
對象我們在前面也簡單介紹過,它是一種將多個數(shù)據(jù)值集中在一個單元的東西,使用名字來存取,它是一個無序的屬性集合2012-04-04
一文帶你走進js數(shù)據(jù)類型與數(shù)據(jù)結構的世界
這篇文章主要介紹了js-數(shù)據(jù)類型與數(shù)據(jù)結構,文章具有一定的參考學習價值,需要的朋友可以學習一下這篇文章中的內(nèi)容2021-08-08

