Search code examples
javascriptclassconstructorjsdoc

jsdoc should be before class or constructor in javascript?


I'm using VScode (but it should be the same in any code editor), and in the following code, when I hover over Circle, it shows me the contents of the jsdoc I've written, but doesn't show them when i hover the parameter radius. What is the issue here?

Is the only way is to write the jsdoc just above the constructor, 'cause that worked in the past?

In short, what is the difference between defining jsdoc before the constructor or the class name

/**
 * This class represents a circle and can calculate its perimeter and area
 * https://en.wikipedia.org/wiki/Circle
 * @constructor
 * @param {number} radius - The radius of the circle.
 */
export default class Circle {
  contructor(radius) {
    this.radius = radius
  }

  perimeter = () => {
    return this.radius * 2 * Math.PI
  }

  area = () => {
    return Math.pow(this.radius, 2) * Math.PI
  }
}

Solution

  • Is the only way is to write the jsdoc just above the constructor, 'cause that worked in the past?

    Yes.

    The documentation for classes shows that the description of the arguments passed to the constructor are specified in documentation on the constructor, not the class.

    /** Class representing a point. */
    class Point {
        /**
         * Create a point.
         * @param {number} x - The x value.
         * @param {number} y - The y value.
         */
        constructor(x, y) {
            // ...
        }
    

    It also states:

    You don't need to use tags such as @class and @constructor with ES 2015 classes—JSDoc automatically identifies classes and their constructors simply by parsing your code.

    @constructor is for use when writing traditional constructor functions without the class keyword.