通用编码标准
-
有意义的名字:
- 使用有意义且具有描述性的变量和函数名称。
- 除了循环计数器之外,避免使用缩写和单字母名称。
// good
const userage = 25;
function calculatetotalprice(items) { ... }
// bad
const a = 25;
function calc(items) { ... }
-
一致的命名约定:
- 变量和函数使用驼峰命名法。
- 使用 pascalcase 命名类名。
const userage = 25;
function calculatetotalprice(items) { ... }
class userprofile { ... }
-
避免重复:
- 遵循 dry(don’t repeat yourself)原则,将重复的代码封装到函数中。
// good
function calculatediscount(price, discount) { ... }
const price1 = calculatediscount(100, 10);
const price2 = calculatediscount(200, 20);
// bad
const price1 = 100 - 10;
const price2 = 200 - 20;
-
错误处理:
- 将 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);
}
}
-
边缘情况:
- 始终考虑边缘情况并验证输入。
function getuserage(user) {
if (!user || !user.age) {
return 'age not available';
}
return user.age;
}
-
一致的格式:
- 遵循一致的代码格式风格(缩进、间距等)。使用 prettier 等工具来自动化此操作。
if (condition) {
dosomething();
} else {
dosomethingelse();
}
代码组织
-
模块化:
- 将代码分解为小的、可重用的模块或函数。
// utils.js
export function calculatediscount(price, discount) { ... }
// main.js
import { calculatediscount } from './utils.js';
-
关注点分离:
- 将不同的关注点(例如,ui 逻辑、业务逻辑、数据处理)分离到不同的文件或函数中。
// 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 和异步/等待进行错误处理:
- 更喜欢使用 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));
}
-
对象解构:
- 使用对象解构以简洁的方式从对象中提取多个属性。
// Good
const vehicle = { make: 'Toyota', model: 'Camry' };
const { make, model } = vehicle;
// Bad
const vehicleMake = vehicle.make;
const vehicleModel = vehicle.model;
通过遵循这些标准,您可以确保您的 javascript 代码干净、可维护且高效。