4.1 [推荐] 单行注释使用 //
注释应单独一行写在被注释对象的上方, 不要追加在某条语句的后面:
- // bad
- const active = true; // is current tab
- // good
- // is current tab
- const active = true;
注释行的上方需要有一个空行 (除非注释行上方是一个块的顶部), 以增加可读性:
- // bad
- function getType() {
- console.log('fetching type...');
- // set the default type to 'no type'
- const type = this.type || 'no type';
- return type;
- }
- // good
- function getType() {
- console.log('fetching type...');
- // set the default type to 'no type'
- const type = this.type || 'no type';
- return type;
- }
- // good
- // 注释行上面是一个块的顶部时不需要空行
- function getType() {
- // set the default type to 'no type'
- const type = this.type || 'no type';
- return type;
- }
4.2 [推荐] 多行注释使用 /** ... */, 而不是多行的 //
- // bad
- // make() returns a new element
- // based on the passed in tag name
- function make(tag) {
- // ...
- return element;
- }
- // good
- /**
- * make() returns a new element
- * based on the passed-in tag name
- */
- function make(tag) {
- // ...
- return element;
- }
4.3 [强制] 注释内容和注释符之间需要有一个空格, 以增加可读性. eslint: spaced-comment
- // bad
- //is current tab
- const active = true;
- // good
- // is current tab
- const active = true;
- // bad
- /**
- *make() returns a new element
- *based on the passed-in tag name
- */
- function make(tag) {
- // ...
- return element;
- }
- // good
- /**
- * make() returns a new element
- * based on the passed-in tag name
- */
- function make(tag) {
- // ...
- return element;
- }
4.4 [推荐] 使用特殊注释标记
有时我们发现某个可能的 bug, 但因为一些原因还没法修复; 或者某个地方还有一些待完成的功能, 这时我们需要使用相应的特殊标记注释来告知未来的自己或合作者. 常用的特殊标记有两种:
- // FIXME: 说明问题是什么
- // TODO: 说明还要做什么或者问题的解决方案
- class Calculator extends Abacus {
- constructor() {
- super();
- // FIXME: shouldn't use a global here
- total = 0;
- // TODO: total should be configurable by an options param
- this.total = 0;
- }
- }
4.5 [推荐] 文档类注释, 如函数, 类, 文件, 事件等, 使用 jsdoc 规范
例如:
- /**
- * Book 类, 代表一个书本.
- * @constructor
- * @param {string} title - 书本的标题.
- * @param {string} author - 书本的作者.
- */
- function Book(title, author) {
- this.title=title;
- this.author=author;
- }
- Book.prototype={
- /**
- * 获取书本的标题
- * @returns {string|*}
- */
- getTitle:function(){
- return this.title;
- },
- /**
- * 设置书本的页数
- * @param pageNum {number} 页数
- */
- setPageNum:function(pageNum){
- this.pageNum=pageNum;
- }
- };
05 工具
我们可以使用一些工具来保证注释质量, 例如:
Eslint: 保证一致的注释风格
ESLint 是当下最流行的 JS 代码检查工具, ESLint 中有一些注释相关的规则, 用户可选择开启:
来源: https://juejin.im/post/5ad9e73ef265da0b873a0ecc