# JavaScript 命名规范
JavaScript 代码整洁之道 (opens new window)
# 变量
命名方法:小驼峰式命名法。
命名规范:前缀应当是名词。(函数的名字前缀为动词,以此区分变量和函数)
命名建议:尽量在变量名字中体现所属类型,如:length、count等表示数字类型;而包含name、title表示为字符串类型。
// good
let maxCount = 10;
let tableTitle = 'LoginTable';
// bad
let setCount = 10;
let getTitle = 'LoginTable';
1
2
3
4
5
6
2
3
4
5
6
# 常量
仅适用于常量定义,用const进行解构等方式不适用此规范 命名方法:名称全部大写。 命名规范:使用大写字母和下划线来组合命名,下划线用以分割单词。
const MAX_COUNT = 10;
const URL = 'http://www.demogic.com';
1
2
2
# 函数
命名方法:小驼峰式命名法。
命名规范:前缀应当为动词。
命名建议:可使用常见动词约定
动词 | 含义 | 返回值 |
---|---|---|
can | 判断是否可执行某个动作(权限) | 函数返回一个布尔值。true:可执行;false:不可执行 |
has | 判断是否含有某个值 | 函数返回一个布尔值。true:含有此值;false:不含有此值 |
is | 判断是否为某个值 | 函数返回一个布尔值。true:为某个值;false:不为某个值 |
get | 获取某个值 | 函数返回一个非布尔值 |
set | 设置某个值 | 无返回值、返回是否设置成功或者返回链式对象 |
load | 加载某些数据 | 无返回值或者返回是否加载完成的结果 |
// 是否可阅读
function canRead(): boolean {
return true;
}
// 获取名称
function getName(): string {
return this.name;
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 类 & 构造函数
命名方法:大驼峰式命名法,首字母大写。
命名规范:前缀为名称。
class Person {
public name: string;
constructor(name) {
this.name = name;
}
}
const person = new Person('bob');
1
2
3
4
5
6
7
2
3
4
5
6
7
# 类的成员
类的成员包含:
公共属性和方法:跟变量和函数的命名一样。
私有属性和方法:前缀为_(下划线),后面跟公共属性和方法一样的命名方式。
class Person {
private _name: string;
constructor() { }
// 公共方法
getName() {
return this._name;
}
// 公共方法
setName(name) {
this._name = name;
}
}
const person = new Person();
person.setName('bob');
person.getName(); // -&bob
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
← CSS 规范 editorconfig →