Search code examples
javascriptjsdoc

How to jsdoc constructor function returning a new object properly?


For example I have a code like this:

export { createPerson }
const createPerson = (name, age) => {
  const getFullData = () => {
    return `Person ${name} is ${age} years old`
  }
  return {
    get name() {
      return "Person name is " + name
    },
    age,
    getFullData,
  }
}

I tried to document it like this:

/**
 * @module people
 */
export { createPerson }
/**
 * Generates a new Person
 * @param {string} name Person name
 * @param {number} age Person age
 * @returns {Person}
 */
const createPerson = (name, age) => {
  /**
   * Gets full data for this person
   */
  const getFullData = () => {
    return `Person ${name} is ${age} years old`
  }
  /**
   * A Person
   * @constructs Person
   */
  const person = {
    /**
     * Name string
     * @type {string}
     */
    get name() {
      return 'Person name is' + name
    },
    /**
     * @prop {number}
     */
    age,
    /**
     * @method
     */
    getFullData,
  }

  return person
}

With code like this I get a proper documentation of the constructor function createPerson with the returning type link to Person, where I see all of it's props and methods.

But I don't see getFullData and age documentation. All @borrows variants I tryed didn't work. @inheritdocs don't work either. How can I get it without copying documentation? Because in a real code there are too many methods returned from the constructor and doc-copying will make a mess and it's too ugly by it's essence to duplicate docs.


Solution

  • I found a way to do what I want! It's @borrows. I just didn't read documentation carefully before — that part concerning naming and pathing in JSDoc system. And here is a working solution:

    /**
     * @module people
     */
    export { createPerson }
    
    /**
     * Generates a new Person
     * @param {string} name Person name
     * @param {number} age Person age
     * @returns {Person}
     */
    const createPerson = (name, age) => {
      /**
       * Gets full data for this person
       * @returns {string}
       */
      const getFullData = () => {
        return `Person ${name} is ${age} years old`
      }
      /**
       * @constructs Person
       * @borrows module:people~createPerson~getFullData as getFullData
       */
      const person = {
        /**
         * Name text
         * @type {string}
         */
        get name() {
          return 'Person name is' + name
        },
        /**
         * @prop {number}
         */
        age,
        getFullData,
      }
    
      return person
    }
    

    Now getFullData method's documentation is inherited, but I still need to document the age prop. Age wasn't initialized in the createPerson code, so I cannot borrow it from there.