一篇文章教你寫出干凈的JavaScript代碼
一段干凈的代碼,你在閱讀、重用和重構(gòu)的時(shí)候都能非常輕松。編寫干凈的代碼非常重要,因?yàn)樵谖覀內(nèi)粘5墓ぷ髦?,你不是僅僅是在為自己寫代碼。實(shí)際上,你還需要考慮一群需要理解、編輯和構(gòu)建你的代碼的同事。
1. 變量
使用有意義的名稱
變量的名稱應(yīng)該是可描述,有意義的, JavaScript 變量都應(yīng)該采用駝峰式大小寫 ( camelCase) 命名。
// Don't ❌ const foo = "JDoe@example.com"; const bar = "John"; const age = 23; const qux = true; // Do ✅ const email = "John@example.com"; const firstName = "John"; const age = 23; const isActive = true
布爾變量通常需要回答特定問(wèn)題,例如:
isActive
didSubscribe
hasLinkedAccount
避免添加不必要的上下文
當(dāng)對(duì)象或類已經(jīng)包含了上下文的命名時(shí),不要再向變量名稱添加冗余的上下文。
// Don't ❌ const user = { userId: "296e2589-7b33-400a-b762-007b730c8e6d", userEmail: "JDoe@example.com", userFirstName: "John", userLastName: "Doe", userAge: 23, }; user.userId; // Do ✅ const user = { id: "296e2589-7b33-400a-b762-007b730c8e6d", email: "JDoe@example.com", firstName: "John", lastName: "Doe", age: 23, }; user.id;
避免硬編碼值
確保聲明有意義且可搜索的常量,而不是直接插入一個(gè)常量值。全局常量可以采用 SCREAMING_SNAKE_CASE 風(fēng)格命名。
// Don't ❌ setTimeout(clearSessionData, 900000); // Do ✅ const SESSION_DURATION_MS = 15 * 60 * 1000; setTimeout(clearSessionData, SESSION_DURATION_MS);
2. 函數(shù)
使用有意義的名稱
函數(shù)名稱需要描述函數(shù)的實(shí)際作用,即使很長(zhǎng)也沒(méi)關(guān)系。函數(shù)名稱通常使用動(dòng)詞,但返回布爾值的函數(shù)可能是個(gè)例外 — 它可以采用 是或否 問(wèn)題的形式,函數(shù)名也應(yīng)該是駝峰式的。
// Don't ❌ function toggle() { // ... } function agreed(user) { // ... } // Do ✅ function toggleThemeSwitcher() { // ... } function didAgreeToAllTerms(user) { // ... }
使用默認(rèn)參數(shù)
默認(rèn)參數(shù)比 && || 或在函數(shù)體內(nèi)使用額外的條件語(yǔ)句更干凈。
// Don't ❌ function printAllFilesInDirectory(dir) { const directory = dir || "./"; // ... } // Do ✅ function printAllFilesInDirectory(dir = "./") { // ... }
限制參數(shù)的數(shù)量
盡管這條規(guī)則可能有爭(zhēng)議,但函數(shù)最好是有3個(gè)以下參數(shù)。如果參數(shù)較多可能是以下兩種情況之一:
- 該函數(shù)做的事情太多,應(yīng)該拆分。
- 傳遞給函數(shù)的數(shù)據(jù)以某種方式相關(guān),可以作為專用數(shù)據(jù)結(jié)構(gòu)傳遞。
// Don't ❌ function sendPushNotification(title, message, image, isSilent, delayMs) { // ... } sendPushNotification("New Message", "...", "http://...", false, 1000); // Do ✅ function sendPushNotification({ title, message, image, isSilent, delayMs }) { // ... } const notificationConfig = { title: "New Message", message: "...", image: "http://...", isSilent: false, delayMs: 1000, }; sendPushNotification(notificationConfig);
避免在一個(gè)函數(shù)中做太多事情
一個(gè)函數(shù)應(yīng)該一次做一件事,這有助于減少函數(shù)的大小和復(fù)雜性,使測(cè)試、調(diào)試和重構(gòu)更容易。
/ Don't ❌ function pingUsers(users) { users.forEach((user) => { const userRecord = database.lookup(user); if (!userRecord.isActive()) { ping(user); } }); } // Do ✅ function pingInactiveUsers(users) { users.filter(!isUserActive).forEach(ping); } function isUserActive(user) { const userRecord = database.lookup(user); return userRecord.isActive(); }
避免使用布爾標(biāo)志作為參數(shù)
函數(shù)含有布爾標(biāo)志的參數(shù)意味這個(gè)函數(shù)是可以被簡(jiǎn)化的。
// Don't ❌ function createFile(name, isPublic) { if (isPublic) { fs.create(`./public/${name}`); } else { fs.create(name); } } // Do ✅ function createFile(name) { fs.create(name); } function createPublicFile(name) { createFile(`./public/${name}`); }
避免寫重復(fù)的代碼
如果你寫了重復(fù)的代碼,每次有邏輯改變,你都需要改動(dòng)多個(gè)位置。
// Don't ❌ function renderCarsList(cars) { cars.forEach((car) => { const price = car.getPrice(); const make = car.getMake(); const brand = car.getBrand(); const nbOfDoors = car.getNbOfDoors(); render({ price, make, brand, nbOfDoors }); }); } function renderMotorcyclesList(motorcycles) { motorcycles.forEach((motorcycle) => { const price = motorcycle.getPrice(); const make = motorcycle.getMake(); const brand = motorcycle.getBrand(); const seatHeight = motorcycle.getSeatHeight(); render({ price, make, brand, nbOfDoors }); }); } // Do ✅ function renderVehiclesList(vehicles) { vehicles.forEach((vehicle) => { const price = vehicle.getPrice(); const make = vehicle.getMake(); const brand = vehicle.getBrand(); const data = { price, make, brand }; switch (vehicle.type) { case "car": data.nbOfDoors = vehicle.getNbOfDoors(); break; case "motorcycle": data.seatHeight = vehicle.getSeatHeight(); break; } render(data); }); }
避免副作用
在 JavaScript 中,你應(yīng)該更喜歡函數(shù)式模式而不是命令式模式。換句話說(shuō),大多數(shù)情況下我們都應(yīng)該保持函數(shù)純。副作用可能會(huì)修改共享狀態(tài)和資源,從而導(dǎo)致一些奇怪的問(wèn)題。所有的副作用都應(yīng)該集中管理,例如你需要更改全局變量或修改文件,可以專門寫一個(gè) util 來(lái)做這件事。
// Don't ❌ let date = "21-8-2021"; function splitIntoDayMonthYear() { date = date.split("-"); } splitIntoDayMonthYear(); // Another function could be expecting date as a string console.log(date); // ['21', '8', '2021']; // Do ✅ function splitIntoDayMonthYear(date) { return date.split("-"); } const date = "21-8-2021"; const newDate = splitIntoDayMonthYear(date); // Original vlaue is intact console.log(date); // '21-8-2021'; console.log(newDate); // ['21', '8', '2021'];
另外,如果你將一個(gè)可變值傳遞給函數(shù),你應(yīng)該直接克隆一個(gè)新值返回,而不是直接改變?cè)撍?/p>
// Don't ❌ function enrollStudentInCourse(course, student) { course.push({ student, enrollmentDate: Date.now() }); } // Do ✅ function enrollStudentInCourse(course, student) { return [...course, { student, enrollmentDate: Date.now() }]; }
3. 條件語(yǔ)句
使用非負(fù)條件
// Don't ❌ function isUserNotVerified(user) { // ... } if (!isUserNotVerified(user)) { // ... } // Do ✅ function isUserVerified(user) { // ... } if (isUserVerified(user)) { // ... }
盡可能使用簡(jiǎn)寫
// Don't ❌ if (isActive === true) { // ... } if (firstName !== "" && firstName !== null && firstName !== undefined) { // ... } const isUserEligible = user.isVerified() && user.didSubscribe() ? true : false; // Do ✅ if (isActive) { // ... } if (!!firstName) { // ... } const isUserEligible = user.isVerified() && user.didSubscribe();
避免過(guò)多分支
盡早 return 會(huì)使你的代碼線性化、更具可讀性且不那么復(fù)雜。
// Don't ❌ function addUserService(db, user) { if (!db) { if (!db.isConnected()) { if (!user) { return db.insert("users", user); } else { throw new Error("No user"); } } else { throw new Error("No database connection"); } } else { throw new Error("No database"); } } // Do ✅ function addUserService(db, user) { if (!db) throw new Error("No database"); if (!db.isConnected()) throw new Error("No database connection"); if (!user) throw new Error("No user"); return db.insert("users", user); }
優(yōu)先使用 map 而不是 switch 語(yǔ)句
既能減少?gòu)?fù)雜度又能提升性能。
// Don't ❌ const getColorByStatus = (status) => { switch (status) { case "success": return "green"; case "failure": return "red"; case "warning": return "yellow"; case "loading": default: return "blue"; } }; // Do ✅ const statusColors = { success: "green", failure: "red", warning: "yellow", loading: "blue", }; const getColorByStatus = (status) => statusColors[status] || "blue";
使用可選鏈接
const user = { email: "JDoe@example.com", billing: { iban: "...", swift: "...", address: { street: "Some Street Name", state: "CA", }, }, }; // Don't ❌ const email = (user && user.email) || "N/A"; const street = (user && user.billing && user.billing.address && user.billing.address.street) || "N/A"; const state = (user && user.billing && user.billing.address && user.billing.address.state) || "N/A"; // Do ✅ const email = user?.email ?? "N/A"; const street = user?.billing?.address?.street ?? "N/A"; const street = user?.billing?.address?.state ?? "N/A";
4.并發(fā)
避免回調(diào)
回調(diào)很混亂,會(huì)導(dǎo)致代碼嵌套過(guò)深,使用 Promise 替代回調(diào)。
// Don't ❌ getUser(function (err, user) { getProfile(user, function (err, profile) { getAccount(profile, function (err, account) { getReports(account, function (err, reports) { sendStatistics(reports, function (err) { console.error(err); }); }); }); }); }); // Do ✅ getUser() .then(getProfile) .then(getAccount) .then(getReports) .then(sendStatistics) .catch((err) => console.error(err)); // or using Async/Await ✅✅ async function sendUserStatistics() { try { const user = await getUser(); const profile = await getProfile(user); const account = await getAccount(profile); const reports = await getReports(account); return sendStatistics(reports); } catch (e) { console.error(err); } }
5. 錯(cuò)誤處理
處理拋出的錯(cuò)誤和 reject 的 promise
/ Don't ❌ try { // Possible erronous code } catch (e) { console.log(e); } // Do ✅ try { // Possible erronous code } catch (e) { // Follow the most applicable (or all): // 1- More suitable than console.log console.error(e); // 2- Notify user if applicable alertUserOfError(e); // 3- Report to server reportErrorToServer(e); // 4- Use a custom error handler throw new CustomError(e); }
6.注釋
只注釋業(yè)務(wù)邏輯
可讀的代碼使你免于過(guò)度注釋,因此,你應(yīng)該只注釋復(fù)雜的邏輯。
// Don't ❌ function generateHash(str) { // Hash variable let hash = 0; // Get the length of the string let length = str.length; // If the string is empty return if (!length) { return hash; } // Loop through every character in the string for (let i = 0; i < length; i++) { // Get character code. const char = str.charCodeAt(i); // Make the hash hash = (hash << 5) - hash + char; // Convert to 32-bit integer hash &= hash; } } // Do ✅ function generateHash(str) { let hash = 0; let length = str.length; if (!length) { return hash; } for (let i = 0; i < length; i++) { const char = str.charCodeAt(i); hash = (hash << 5) - hash + char; hash = hash & hash; // Convert to 32bit integer } return hash; }
使用版本控制
在代碼里不需要保留歷史版本的注釋,想查的話你直接用 git log 就可以搜到。。
// Don't ❌ /** * 2021-7-21: Fixed corner case * 2021-7-15: Improved performance * 2021-7-10: Handled mutliple user types */ function generateCanonicalLink(user) { // const session = getUserSession(user) const session = user.getSession(); // ... } // Do ✅ function generateCanonicalLink(user) { const session = user.getSession(); // ... }
好了,去寫出你漂亮的代碼吧!🌈
總結(jié)
到此這篇關(guān)于如何寫出干凈的JavaScript代碼的文章就介紹到這了,更多相關(guān)寫干凈的JavaScript代碼內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解nuxt 微信公眾號(hào)支付遇到的問(wèn)題與解決
這篇文章主要介紹了詳解nuxt 微信公眾號(hào)支付遇到的問(wèn)題與解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08alert中斷settimeout計(jì)時(shí)功能
在測(cè)試過(guò)程中發(fā)現(xiàn)alert會(huì)中斷settimeout的計(jì)時(shí)功能,關(guān)閉對(duì)話框后,settimeout的時(shí)間會(huì)重頭開(kāi)始計(jì)時(shí),而不是從中斷處,感興趣的朋友可以了解下2013-07-07JS對(duì)象數(shù)組去重的3種方法示例及對(duì)比
這篇文章主要給大家介紹了關(guān)于JS對(duì)象數(shù)組去重的3種方法,三種方法分別包括使用filter和Map、使用reduce以及for循環(huán),文中每個(gè)方法都給出了示例代碼,需要的朋友可以參考下2021-07-07javascript實(shí)現(xiàn)tab切換的四種方法
這篇文章主要為大家詳細(xì)介紹了javascript實(shí)現(xiàn)tab切換的四種方法,并且對(duì)每個(gè)方法進(jìn)行了評(píng)價(jià),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2015-11-11Bootstrap Metronic完全響應(yīng)式管理模板之菜單欄學(xué)習(xí)筆記
這篇文章主要介紹了Bootstrap Metronic完全響應(yīng)式管理模板之菜單欄學(xué)習(xí)筆記,感興趣的小伙伴們可以參考一下2016-07-07使用JavaScript實(shí)現(xiàn)計(jì)算顏色的相對(duì)亮度并確定相應(yīng)的文本顏色
這篇文章主要為大家詳細(xì)介紹了如何使用JavaScript實(shí)現(xiàn)計(jì)算顏色的相對(duì)亮度并確定相應(yīng)的文本顏色,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-04-04javascript 星級(jí)評(píng)分效果(手寫)
今天上午抽空隨手寫了個(gè)星級(jí)評(píng)分的效果,給大家分享下。由于水平有限,如有問(wèn)題請(qǐng)指出;首先要準(zhǔn)備一張星星的圖片,灰色是默認(rèn)狀態(tài),黃色是選擇狀態(tài),需要的朋友可以參考下2012-12-12