3.1 语法
3.1.1 区分大小写
- ECMAScript 中的一切(变量、函数名和操作符)都区分大小写。
3.1.2 标识符
- 所谓标识符,就是指变量、函数、属性的名字,或者函数的参数。标识符可以按照下列格式规则组合起来的一或多个字符:
- 第一个字符必须是一个字母、下划线(_)或一个美元符号($);
- 其他字符可以是字母、下划线、美元符号或数字。
- 标识符中的字符也可以包含扩展的ASCII或Unicode字母字符,但不推荐这样。
- 按照惯例,ECMAScipt 标识符采用驼峰大小写格式。
命名规范:
- 避免单字母名字。命名需要有可描述性。eslint: id-length
//bad
function q() {}
//good
function query() {}
- 命名对象,函数和实例时使用驼峰风格。eslint: camelcase jscs: requireCamelCaseOrUpperCaseIdentifiers
//bad
const OBJEcttsssss = {};
const this_is_my_object = {};
function c() {}
//good
const thisIsMyObject = {};
function thisIsMyFuntion() {}
- 仅当命名构造函数或类的时候使用帕斯卡风格。eslint: new-cap
//bad
function user(options) {
this.name = options.name;
}
cosnt bad = new user({
name: 'nope',
});
//good
class User {
constructor(options) {
this.name = option.name;
}
}
const good = new User({
name: 'yup',
});
- 不要使用下划线开头或结尾。eslint: no-underscore-dangle
原因:JavaScript对于属性和方法并没有隐私的概念.尽管下划线开头通常意味着’private’, 事实上这些属性是完全公开的,是公开API的一部分. 这种风格可能导致开发者错误地认为这不重要或者测试也不必要. 也就是说: 如果你想让其 “private”, 必须使其不可见.
//bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
this._firstName = 'Panda';
//good
this.firstName = 'Panda';
//good, in environments where WeakMaps are avilable
//see https://kangax.github.io/compat-table/es6/#test-WeakMap
const firstNames = new WeakMap();
firstNames.set(this, 'Panda');
- 不要保存指向
this
的引用。使用箭头函数或函数的#bind。
//bad
function foo() {
const self = this;
return function () {
console.log(self);
};
}
//bad
function foo() {
const that = this;
return function () {
console.log(that);
};
}
//good
function foo() {
return () => {
console.log(this);
};
}