JavaScript 编程规范
Posted 飞翔的熊blabla
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript 编程规范相关的知识,希望对你有一定的参考价值。
数字:使用 Number 进行转换,而 parseInt 则始终以基数解析字串。
eslint: radix no-new-wrappers
const inputValue = '4';
// bad
const val = new Number(inputValue);
// bad
const val = +inputValue;
// bad
const val = inputValue >> 0;
// bad
const val = parseInt(inputValue);
// good
const val = Number(inputValue);
// good
const val = parseInt(inputValue, 10);
布尔值:
eslint: no-new-wrappers
const age = 0;
// bad
const hasAge = new Boolean(age);
// good
const hasAge = Boolean(age);
// best
const hasAge = !!age;
命名规则 Naming Conventions
1. 避免使用单字母名称。使你的命名具有描述性。
eslint: id-length
// bad
function q() {
// ...
}
// good
function query() {
// ...
}
2. 当命名对象,函数和实例时使用驼峰式命名。
eslint: camelcase jscs: requireCamelCaseOrUpperCaseIdentifiers
// bad
const OBJEcttsssss = {};
const this_is_my_object = {};
function c() {}
// good
const thisIsMyObject = {};
function thisIsMyFunction() {}
3. 当命名构造函数或类的时候使用 PascalCase 式命名,(注:即单词首字母大写)。
eslint: new-cap
// bad
function user(options) {
this.name = options.name;
}
const bad = new user({
name: 'nope',
});
// good
class User {
constructor(options) {
this.name = options.name;
}
}
const good = new User({
name: 'yup',
});
4. 当 导出(export) 一个默认函数时使用驼峰式命名。你的文件名应该和你的函数的名字一致。
function makeStyleGuide() {
// ...
}
export default makeStyleGuide;
5. 当导出一个构造函数 / 类 / 单例 / 函数库 / 纯对象时使用 PascalCase 式命名。
const AirbnbStyleGuide = {
es6: {
},
};
export default AirbnbStyleGuide;
存取器 Accessors
属性的存取器函数不是必须的。
1. 別使用 JavaScript 的 getters/setters,因为它们会导致意想不到的副作用,而且很难测试,维护和理解。相反,如果要使用存取器函数,使用 getVal() 及 setVal(‘hello’)。
// bad
class Dragon {
get age() {
// ...
}
set age(value) {
// ...
}
}
// good
class Dragon {
getAge() {
// ...
}
setAge(value) {
// ...
}
}
2. 如果属性/方法是一个 boolean, 使用 isVal() 或 hasVal() 方法。
// bad
if (!dragon.age()) {
return false;
}
// good
if (!dragon.hasAge()) {
return false;
}
以上是关于JavaScript 编程规范的主要内容,如果未能解决你的问题,请参考以下文章