如何记录构造函数生成具有哪些属性(以及方法)的对象?

How to document that a constructor function generates objects which have what properties (and also methods)?

我有一个构造函数,我正在使用 JSDoc 来记录它:

/**
 * @constructor
 * @param {String} title The title of the task
 * @param {Boolean} important Whether the task is important of not
 */
function Task(title, important) {
    this.title = title
    this.important = important

    // 1 presents to 'unfinished', 2 presents to 'processing', 3 presents to 'finished'
    this.state = 1
}

文档生成:

但有一件事。您在我的构造函数中看到,它有一个名为 state 的 属性,并且没有参数用于设置 state 属性 的值。

因此,当我记录这个 Task 构造函数时,我不知道如何告诉读者这个函数生成具有 state 属性 的对象。顺便说一下,我认为开发人员在阅读文档时会知道此 Task 函数生成的对象具有 titleimportant 属性,因为这些属性记录在参数下.而且由于 state 属性 它不“依赖”任何参数,我不知道如何在文档中显示它。

为您的 Task 对象添加 @typedef 类型定义:

/**
 * @typedef {object} Task
 * @property {string} title The title of the task
 * @property {boolean} important Whether the task is important of not
 * @property {number} state 1 represents 'unfinished', 2 represents 'processing', 3 represents 'finished'
 */

并在构造函数文档中添加 @returns

/**
 * @constructor
 * @param {String} title The title of the task
 * @param {Boolean} important Whether the task is important of not
 * @returns {Task} a task object
 */
function Task(title, important) {
    this.title = title
    this.important = important

    // 1 presents to 'unfinished', 2 presents to 'processing', 3 presents to 'finished'
    this.state = 1
}