首頁  >  文章  >  web前端  >  通用編碼標準 JavaScript。

通用編碼標準 JavaScript。

王林
王林原創
2024-08-06 18:33:401165瀏覽

General Coding Standards JavaScript.

通用編碼標準

  1. 有意義的名字:
    • 使用有意義且具有描述性的變數和函數名稱。
    • 除了循環計數器之外,避免使用縮寫和單字母名稱。
   // Good
   const userAge = 25;
   function calculateTotalPrice(items) { ... }

   // Bad
   const a = 25;
   function calc(items) { ... }
  1. 一致的命名約定:
    • 變數和函數使用駝峰命名法。
    • 使用 PascalCase 命名類別名稱。
   const userAge = 25;
   function calculateTotalPrice(items) { ... }
   class UserProfile { ... }
  1. 避免重複:
    • 遵循 DRY(不要重複自己)原則,將重複的程式碼封裝到函數中。
   // Good
   function calculateDiscount(price, discount) { ... }
   const price1 = calculateDiscount(100, 10);
   const price2 = calculateDiscount(200, 20);

   // Bad
   const price1 = 100 - 10;
   const price2 = 200 - 20;
  1. 錯誤處理:
    • 將 API 呼叫和其他非同步操作包裝在 try-catch 區塊中。
   async function fetchData() {
     try {
       const response = await fetch('api/url');
       const data = await response.json();
       return data;
     } catch (error) {
       console.error('Error fetching data:', error);
     }
   }
  1. 邊緣情況:
    • 始終考慮邊緣情況並驗證輸入。
   function getUserAge(user) {
     if (!user || !user.age) {
       return 'Age not available';
     }
     return user.age;
   }
  1. 一致的格式:
    • 遵循一致的程式碼格式風格(縮排、間距等)。使用 Prettier 等工具來自動化此操作。
   if (condition) {
     doSomething();
   } else {
     doSomethingElse();
   }

代碼組織

  1. 模組化:
    • 將程式碼分解為小的、可重複使用的模組或函數。
   // utils.js
   export function calculateDiscount(price, discount) { ... }

   // main.js
   import { calculateDiscount } from './utils.js';
  1. 關注點分離:
    • 將不同的關注點(例如,UI 邏輯、業務邏輯、資料處理)分開到不同的檔案或函數中。
   // ui.js
   function updateUI(data) { ... }

   // data.js
   async function fetchData() { ... }

   // main.js
   import { updateUI } from './ui.js';
   import { fetchData } from './data.js';

最佳實踐

  1. 使用嚴格模式:
    • 始終啟用嚴格模式以捕獲常見的編碼錯誤。
   'use strict';
  1. 使用常數:
    • 對不改變的值使用常數。
   const MAX_USERS = 100;
  1. 避免全域變數:
    • 最小化全域變數的使用以避免衝突和意外行為。
   // Good
   (function() {
     const localVariable = 'This is local';
   })();

   // Bad
   var globalVariable = 'This is global';
  1. 評論與文件:
    • 編寫註解和文件來解釋程式碼的目的和功能。
   /**
    * Calculates the total price after applying a discount.
    * @param {number} price - The original price.
    * @param {number} discount - The discount to apply.
    * @returns {number} - The total price after discount.
    */
   function calculateTotalPrice(price, discount) { ... }
  1. 使用 Promises 和非同步/等待進行錯誤處理:
    • 偏好使用 Promise 和 async/await 進行非同步操作,並將它們包裝在 try-catch 區塊中以進行錯誤處理。
   // Good
   async function fetchData() {
     try {
       const response = await fetch('api/url');
       const data = await response.json();
       return data;
     } catch (error) {
       console.error('Error fetching data:', error);
     }
   }

   // Bad
   function fetchData(callback) {
     fetch('api/url')
       .then(response => response.json())
       .then(data => callback(data))
       .catch(error => console.error('Error fetching data:', error));
   }
  1. 物件解構:
    • 使用物件解構以簡潔的方式從物件中提取多個屬性。
   // Good
   const vehicle = { make: 'Toyota', model: 'Camry' };
   const { make, model } = vehicle;

   // Bad
   const vehicleMake = vehicle.make;
   const vehicleModel = vehicle.model;

透過遵循這些標準,您可以確保您的 JavaScript 程式碼乾淨、可維護且有效率。

以上是通用編碼標準 JavaScript。的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn