通用编码标准 JavaScript
文章标签
标准
通用编码标准
- 有意义的名字:
// good const userage = 25; function calculatetotalprice(items) { ... } // bad const a = 25; function calc(items) { ... }- 一致的命名约定:
const userage = 25; function calculatetotalprice(items) { ... } class userprofile { ... }- 避免重复:
// good function calculatediscount(price, discount) { ... } const price1 = calculatediscount(100, 10); const price2 = calculatediscount(200, 20); // bad const price1 = 100 - 10; const price2 = 200 - 20;- 错误处理:
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); } }- 边缘情况:
function getuserage(user) { if (!user || !user.age) { return 'age not available'; } return user.age; }- 一致的格式:
if (condition) { dosomething(); } else { dosomethingelse(); }代码组织
- 模块化:
// utils.js export function calculatediscount(price, discount) { ... } // main.js import { calculatediscount } from './utils.js';- 关注点分离:
// ui.js function updateui(data) { ... } // data.js async function fetchdata() { ... } // main.js import { updateui } from './ui.js'; import { fetchdata } from './data.js';最佳实践
- 使用严格模式:
'use strict';
- 使用常量:
const max_users = 100;
- 避免全局变量:
// good (function() { const localvariable = 'this is local'; })(); // bad var globalvariable = 'this is global';- 评论和文档:
/** * 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) { ... }- 使用 promises 和异步/等待进行错误处理:
// 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)); }- 对象解构:
// Good const vehicle = { make: 'Toyota', model: 'Camry' }; const { make, model } = vehicle; // Bad const vehicleMake = vehicle.make; const vehicleModel = vehicle.model;通过遵循这些标准,您可以确保您的 javascript 代码干净、可维护且高效。
共享博客