您好,登錄后才能下訂單哦!
小編給大家分享一下如何寫出干凈的JavaScript代碼,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
變量的名稱應該是可描述,有意義的, JavaScript 變量都應該采用駝峰式大小寫 ( 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
布爾變量通常需要回答特定問題,例如:
isActive
didSubscribe
hasLinkedAccount
當對象或類已經包含了上下文的命名時,不要再向變量名稱添加冗余的上下文。
// 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;
確保聲明有意義且可搜索的常量,而不是直接插入一個常量值。全局常量可以采用 SCREAMING_SNAKE_CASE 風格命名。
// Don't ? setTimeout(clearSessionData, 900000); // Do ? const SESSION_DURATION_MS = 15 * 60 * 1000; setTimeout(clearSessionData, SESSION_DURATION_MS);
函數名稱需要描述函數的實際作用,即使很長也沒關系。函數名稱通常使用動詞,但返回布爾值的函數可能是個例外 — 它可以采用 是或否 問題的形式,函數名也應該是駝峰式的。
// Don't ? function toggle() { // ... } function agreed(user) { // ... } // Do ? function toggleThemeSwitcher() { // ... } function didAgreeToAllTerms(user) { // ... }
默認參數比 && || 或在函數體內使用額外的條件語句更干凈。
// Don't ? function printAllFilesInDirectory(dir) { const directory = dir || "./"; // ... } // Do ? function printAllFilesInDirectory(dir = "./") { // ... }
盡管這條規則可能有爭議,但函數最好是有3個以下參數。如果參數較多可能是以下兩種情況之一:
該函數做的事情太多,應該拆分。
傳遞給函數的數據以某種方式相關,可以作為專用數據結構傳遞。
// 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);
一個函數應該一次做一件事,這有助于減少函數的大小和復雜性,使測試、調試和重構更容易。
/ 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(); }
函數含有布爾標志的參數意味這個函數是可以被簡化的。
// 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}`); }
如果你寫了重復的代碼,每次有邏輯改變,你都需要改動多個位置。
// 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 中,你應該更喜歡函數式模式而不是命令式模式。換句話說,大多數情況下我們都應該保持函數純。副作用可能會修改共享狀態和資源,從而導致一些奇怪的問題。所有的副作用都應該集中管理,例如你需要更改全局變量或修改文件,可以專門寫一個 util 來做這件事。
// 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'];
另外,如果你將一個可變值傳遞給函數,你應該直接克隆一個新值返回,而不是直接改變該它。
// Don't ? function enrollStudentInCourse(course, student) { course.push({ student, enrollmentDate: Date.now() }); } // Do ? function enrollStudentInCourse(course, student) { return [...course, { student, enrollmentDate: Date.now() }]; }
// Don't ? function isUserNotVerified(user) { // ... } if (!isUserNotVerified(user)) { // ... } // Do ? function isUserVerified(user) { // ... } if (isUserVerified(user)) { // ... }
// 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();
盡早 return 會使你的代碼線性化、更具可讀性且不那么復雜。
// 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); }
既能減少復雜度又能提升性能。
// 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";
回調很混亂,會導致代碼嵌套過深,使用 Promise 替代回調。
// 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); } }
處理拋出的錯誤和 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); }
可讀的代碼使你免于過度注釋,因此,你應該只注釋復雜的邏輯。
// 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(); // ... }
以上是“如何寫出干凈的JavaScript代碼”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。