jsdoc基本使用方法

293 阅读2分钟

代码中如何按照jsdoc的规范增加注释?

1.页面声明

1.1 增加标签 @module。

我们做以下约定:

1)在module后面的名称中,增加'Page-'前缀,表示主页面,展示在文档左侧的Pages中;

2)若不加'Page-'前缀,表示该组件为公共组件或子页面,展示在文档左侧的Modules中。

例如


/**

* 一个简单的Vue插件

* @module Page-门户首页

*/

生成文档效果如下: image.png

1.2 声明子组件及跳转方法:

在components增加一个注释即可。注意:不要加@

效果如上图下半部分


/**

* components 包含子组件

* @prop {Component} component 子组件1说明

*/

components: { Header },

  


2. 函数声明

函数形式比较多样,主要介绍以下几类:

1)无参数无返回值;

2)有参数;

3)有返回值;

4)有举例说明的;

对于第一类,直接做必要的注释,描述函数作用就可以。可以添加@description

第二类、第三类和第四类,分别增加@param、@returns和@example标签

举个简单的例子


/**

* 获取类目列表

* @vue

* @param {number} a

* @param imgs {Array} 图片集

* @param [size] {Integer} 尺寸

* @author Dana <jxj@example.com>

* @description Add two numbers.

* @example Example usage of formatImgUrl.

* this.formatImgUrl(imgs);

* @returns {Array}

*/

对于不是全局的方法,可以添加@fuction进行注释

例如


/**

* @function remove_all_event

* [ 移除全部监听 ]

* @param {string} eventType [ 事件类型 ]

*/

document.remove_all_event = function (eventType) {

this.eventListeners[eventType] = null;

};

使用@example 编写使用案例

例如


/**

* @module Utils-Event

* @description 事件机制

* @example on:绑定事件

* 单个事件绑定示例

* $_EventLib.on('myEvent',callback)

* 多个事件绑定示例

* $_EventLib.on([{

* eventType:'myEvent',

* callback:cb

* },{

* eventType:'myEvent2',

* callback:cb2

* }])

* dispatch:触发事件

* 示例

* $_EventLib.dispatch('myEvent',{msg:'hello'})

* remove:删除事件

* 单个事件删除示例

* $_EventLib.remove('myEvent')

*

*/

如下图所示

image.png

常用的JSDoc注释:

定义对象类型——@type

定义自定义类型和属性——@typedef和@property/@prop

@param:用于描述函数参数的类型和名称。

@returns:用于描述函数返回值的类型和含义。

@typedef:定义一个新的自定义类型。

@property:用于描述对象属性的类型和含义。

@constructor:用于描述构造函数。

@class:用于描述类和类的成员。

@extends:用于描述类的继承关系。

@private:标记注释为私有的。

@public:标记注释为公共的。

@deprecated:标记注释已经过时或不建议使用。

使用@private和@public注释的例子:


/**

* 计算器类

* @class

*/

class Calculator {

/**

* 创建一个新的计算器对象

* @constructor

* @param {number} x - 初始化值,默认为0

*/

constructor(x = 0) {

/** @private */

this._x = x;

}

  


/**

* 加法运算

* @method

* @param {number} y - 要加的数值

* @returns {number} 当前结果值

*/

add(y) {

this._x += y;

return this._x;

}

  


/**

* 获取当前结果值

* @method

* @public

* @returns {number} 当前结果值

*/

getResult() {

return this._x;

}

}

  


const calculator = new Calculator();

  


console.log(calculator.getResult()); // 输出0

console.log(calculator.add(2)); // 输出2

console.log(calculator.getResult()); // 输出2

  


使用了@private注释来标记_x属性为私有属性,只能在类内部访问。同时,我们使用了@public注释来标记getResult()方法为公共方法,外部代码可以直接调用它。这样做可以使代码更安全、可读性更高,并且提供更好的文档。

其他具体的用法参考jsdoc官方文档 www.jsdoc.com.cn/

`