如何使用JSDoc记录对象?

时间:2018-11-02 16:09:28

标签: javascript jsdoc jsdoc3 code-documentation

使用JSDoc记录简单JavaScript对象(及其导出)的源代码的最佳方法是什么?

例如,我要记录以下对象:

/** how do I JSDocument object baseAdder? */
const baseAdder  = {
    /** how do I JSDocument property base? */
    base: 1,
    /**
     * Add a number to base
     * @param {number} a the number to be added to base
     * @returns {number} the sum of the number plus base
     */
    f: function(a) {
        return this.base + a;
        }
    };

/** how do I JSDocument this export? Should I? */
module.exports = baseAdder;

2 个答案:

答案 0 :(得分:1)

基本的JS Doc文档就是这样。

/*
* {Object} baseAdder - Base Adder object
* {Number} baseAdder.base - Base value
* {function} baseAdder.f - A function f on the Base Adder
*/
const baseAdder  = {
    base: 1,
    /**
     * Add a number to base
     * @param {Number} - a the number to be added to base
     * @returns {Number} - the sum of the number plus base
     */
    f: function(a) {
        return this.base + a;
        }
    };

/**
 * A module of base adder!
 * @module baseAdder
 */
module.exports = baseAdder;

有关更多参考,请遵循官方文档-http://usejsdoc.org/index.html

答案 1 :(得分:0)

<块引用>

在大多数情况下,您的 CommonJS 或 Node.js 模块应该包含一个独立的 JSDoc 注释,其中包含一个 @module 标签。 @module 标签的值应该是传递给 require() 函数的模块标识符。例如,如果用户通过调用 require('my/shirt') 加载模块,则您的 JSDoc 注释将包含标签 @module my/shirt。

Documenting JavaScript Modules

对此的独立 JSDoc 注释是:

/** @module so/answer */

这意味着我们需要您的模块如下:

const adder = require('so/answer');

您的 baseAdder 对象实际上是一个命名空间(参见 @namespace),具有两个静态成员:一个数字和一个函数。

/** @module so/answer */

/** @namespace */
const baseAdder  = {

  /**
   * @type {number}
   * @default 1
   */
  base: 1,

  /**
   * @param {number} a the number to be added to base
   * @return {number} the sum of the number plus base
   */
  f: function(a) {
    return this.base + a;
  }
};

module.exports = baseAdder;

除非明确另有说明,否则一个模块中的所有符号都是该模块的成员。所以你的命名空间现在属于那个模块。

警告:使用 {Number} 而不是 {number} 是一个常见的错误。这是两种不同类型的表达式。第一个是指一个数字对象,例如new Number(42) 和第二个指的是文字数字,例如42

在实践中,查看您的文档的人可能会以任何一种方式假设一个字面数字,但如果您使用基于 JSDoc 的静态类型检查器,这种区别就变得很重要。

如果您有兴趣,另请参阅我的 JSDoc Cheat Sheet


通过 JSDoc 生成的文档是什么样子

索引:

enter image description here

让我们看看你的模块:

enter image description here

让我们看看你的命名空间:

enter image description here