如何使用JSDoc记录对象?

3

如何使用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个回答

3
一个基本的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


谢谢!我之前去过jsdoc网站,但是对于你添加的前5行代码并不是很清晰。一个快速的问题:为什么我们要在顶部和对象内部都记录函数f的文档? - P. Bofs
1
第一个只是元信息,表示该对象具有一个键,其值为函数。在内部实际上定义了预期的参数和返回类型。坦率地说,将其放在何处更多是个人喜好(内部或顶部),两者都同样有效。 - front_end_dev

1
在大多数情况下,您的CommonJS或Node.js模块应包含一个独立的JSDoc注释,其中包含@module标记。@module标记的值应该是传递给require()函数的模块标识符。例如,如果用户通过调用require('my/shirt')加载模块,则您的JSDoc注释将包含标记@module my/shirt。
请参见文档化JavaScript模块 该注释的独立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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接