Reputation: 61
What's the best way to document the source code of a simple JavaScript object (and its export) using JSDoc?
For example, I want to document the following object:
/** 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;
Upvotes: 3
Views: 6024
Reputation: 18891
In most cases, your CommonJS or Node.js module should include a standalone JSDoc comment that contains a @module tag. The @module tag's value should be the module identifier that's passed to the require() function. For example, if users load the module by calling require('my/shirt'), your JSDoc comment would contain the tag @module my/shirt.
See Documenting JavaScript Modules
A standalone JSDoc comment for that would be:
/** @module so/answer */
Meaning that we would require your module as follow:
const adder = require('so/answer');
Your baseAdder
object is actually a namespace (see @namespace
) with two static members: a number and a function.
/** @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;
Unless explicitly documented otherwise, all symbols within a module are members of that module. So your namespace now belongs to that module.
Warning: It is a common mistake to use {Number}
instead of {number}
. These are two different type expressions. The first refers to a number object e.g. new Number(42)
and the second refers to a literal number e.g. 42
.
In practice, people looking at your documentation are likely to assume a literal number either way but this distinction becomes important if you use a static type checker based on JSDoc.
See also my JSDoc Cheat Sheet if you're interested.
What the doc looks like when generated via JSDoc
Index:
Let's see your module:
Let's see your namespace:
Upvotes: 1
Reputation: 2056
A basic JS Doc documentation is like.
/*
* {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;
For more reference follow the official documentation - http://usejsdoc.org/index.html
Upvotes: 3