Home > Back-end >  How to document that a constructor function generates objects which have what properties (and also m
How to document that a constructor function generates objects which have what properties (and also m

Time:11-06

I have a constructor function, and Im using JSDoc to document it:

/**
 * @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
}

The documentation is generated:

enter image description here

But here is a thing. You see in my constructor function, it is has a property with the name of state, and there is no paramater use to set the value of the state property.

And so when I document this Task constructor function, I have no idea how to tell the readers this function generates objects which have a state property. And by the way, I think the developers when they read the documentation, they will know the objects generated by this Task function has the title and important properties is because those properties documented under parameters. And since the state property it doesn't "rely" on any parameter, I don't know how to show it on the documentation.

CodePudding user response:

Add a @typedef type definition for your Task objects:

/**
 * @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'
 */

and add a @returns to your constructor function documentation:

/**
 * @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
}
  • Related