JavaScript 规范
一、代码规范
1.1 变量命名
驼峰命名
使用驼峰命名法(camelCase)为变量命名,避免使用下划线分隔。javascript// Bad let user_name = 'John'; // Good let userName = 'John';
1
2
3
4
5常量全大写
常量使用全大写字母,单词之间用下划线分隔。javascript// Good const MAX_USERS = 100;
1
2语句结束加分号
虽然 JavaScript 中分号是可选的,但为了避免自动插入分号机制(ASI)引发的问题,建议始终在语句末尾加分号。javascript// Good let userName = 'Alice';
1
2布尔值命名
布尔值变量和返回布尔值的函数通常以is
、can
、has
、need
等助动词开头。javascriptconst isVisible = true; const hasLicense = checkHasLicense(fruits, 'apple');
1
2数值命名
首选有意义的简短命名,如width
、length
、count
。如果需要更具体的命名,可采用numberOfXXX
或xxxCount
等通用形式。javascriptlet width; let length; let total; let maxWidth; let numberOfErrors; let errorCount;
1
2
3
4
5
6类名用名词
类名应使用名词,表示一类事物的抽象。javascript// Good class Car {} // Bad class MakeCar {}
1
2
3
4
5字典(Map)命名
字典的命名推荐使用valuesByKey
的形式,避免使用过于宽泛或冗余的命名。javascriptconst usersByID = { id12345: { name: 'byted', age: 9 }, }; // Bad const values = {}; // 提供的信息不够充分 const keysToValuesMap = {}; // 名字里不要体现类型,类型信息交给 TypeScript
1
2
3
4
5
6
7
1.2 函数
函数命名
函数名应以动词开头,表明函数的作用。javascriptfunction getUserInfo() {} function setUserName(name) {}
1
2使用具描述性的名字
- 使用业务术语,避免从计算机视角命名。
- 尽量避免缩略语和黑话。
- 推荐安装
Code Spell Checker
等插件,避免拼写错误。
javascript// Good function getUserPosts() {} // Bad function getUserData() {} // 含义过于宽泛
1
2
3
4
5用词精简但不失语义
选择简洁且明确的命名,避免使用多个近义词。javascript// Good function findUserByNameOrEmail() {} function setUserLoggedInTrue() {} // Bad function getQuestion() {} function returnUsers() {} // 不要频繁更换动词
1
2
3
4
5
6
7在上下文中保持意义明确
命名不应重复上下文信息。javascriptclass Employee { constructor(name) { // Good this.name = name; // Bad this.employeeName = name; // 冗余 } } const employeeName = new Employee('gavin').name;
1
2
3
4
5
6
7
8
9
10
11使用统一的动词
常用动词包括get
、set
、read
、create
、add
、update
、reset
、delete
、remove
等。javascript// Good function getQuestion() {} function getUserPosts() {} // Bad function returnUsers() {} // 不一致的动词
1
2
3
4
5
6函数名采用动词或判断性词汇
函数名通常由一个动词和一个名词组成。javascriptfunction getYear() {} // 取值 function toString() {} // 转换 function isArray() {} // 判断
1
2
3使用箭头函数(在适当场景)
在不需要this
的场景下,使用箭头函数可以提高代码的简洁性。javascript// Good const sum = (a, b) => a + b;
1
2函数参数合理控制
函数参数尽量保持在 3 个以内,超出时可以考虑传入对象。javascript// Good function createUser({ name, age, email }) {}
1
2
1.3 对象与数组
对象属性简写
在 ES6 中,当属性名与变量名相同时,可以使用对象简写语法。javascript// Good const name = 'Alice'; const user = { name }; // 相当于 { name: name }
1
2
3解构赋值
使用解构可以提高代码的可读性,避免反复访问对象或数组属性。javascript// Good const user = { name: 'Alice', age: 25 }; const { name, age } = user;
1
2
3数组扩展运算符
使用扩展运算符代替concat
或push
等方法来合并数组或创建新数组。javascript// Good const arr1 = [1, 2]; const arr2 = [3, 4]; const combined = [...arr1, ...arr2];
1
2
3
4
1.4 条件判断
使用严格相等(
===
和!==
)
严格相等检查避免了类型转换带来的潜在问题。javascript// Bad if (x == 0) {} // Good if (x === 0) {}
1
2
3
4
5短路评估
在逻辑判断中使用短路评估来减少代码的冗余。javascript// Good const isValid = user && user.isActive; // Better const isValid = user?.isActive; const userStatus = { ...(user && { isActive: user.isActive }), };
1
2
3
4
5
6
7
8
9
二、注释规范
单行注释与多行注释
- 单行注释:使用
//
对简单逻辑进行说明。 - 多行注释:使用
/* */
对复杂逻辑进行详细解释。
javascript// This is a single line comment /* This is a multi-line comment. It explains the following block of code. */ function calculateTax(income) { // Tax calculation logic }
1
2
3
4
5
6
7
8
9- 单行注释:使用
避免无意义的注释
注释应解释“为什么”,而不是“是什么”或“怎么做”。避免与代码功能重复。javascript// Bad // This is a function to get the user name function getUserName() {} // Good // Fetches the user name from the database if user is logged in function getUserName() {}
1
2
3
4
5
6
7文档注释(JSDoc)
用于生成 API 文档,描述函数、类、方法、参数和返回值。javascript/** * 这是一个函数,用于计算两个数的和 * @param {number} a 第一个加数 * @param {number} b 第二个加数 * @return {number} 两个数的和 */ function add(a, b) { return a + b; }
1
2
3
4
5
6
7
8
9
三、常见最佳实践
避免魔法数字
将代码中直接使用的数字定义为常量,并给予有意义的名称。javascript// Bad if (score > 60) {} // Good const PASSING_SCORE = 60; if (score > PASSING_SCORE) {}
1
2
3
4
5
6避免全局变量
尽量避免在全局作用域中声明变量,防止与其他脚本冲突。使用模板字符串
使用 ES6 的模板字符串(反引号 ``)避免复杂的字符串拼接,并插入变量和表达式。javascript// Good const message = `Hello, ${userName}. You have ${messages.length} new messages.`;
1
2提前返回减少嵌套
函数中使用“提前返回”来减少嵌套和复杂度。
// Bad
function processUser(user) {
if (user) {
if (user.isActive) {
// Do something
}
}
}
// Good
function processUser(user) {
if (!user || !user.isActive) return
// Do something
}
2
3
4
5
6
7
8
9
10
11
12
13
14