How to document ECMA6 classes with JSDoc? - javascript

Background
I have a project in Nodejs using ECMA6 classes and I am using JSDoc to comment my code, as to make it more accessible to other developers.
However, my comments are not well accepted by the tool, and my documentation is a train wreck.
Problem
My problem is that I don't know how to document ECMA6 classes with JSDoc and I can't find any decent information.
What I tried
I tried reading the official example but I find it lacking and incomplete. My classes have members, constant variables and much more, and I don't usually know which tags to use for what.
I also made an extensive search in the web, but most information I found is prior to 2015 where JSDocs didn't support ECMA6 scripts yet. Recent articles are scarce and don't cover my needs.
The closest thing I found was this GitHub Issue:
https://github.com/jsdoc3/jsdoc/issues/819
But it is outdated by now.
Objective
My main objective is to learn how to document ECMA6 classes in NodeJS with JSDoc.
I have a precise example that I would like to see work properly:
/**
* #fileOverview What is this file for?
* #author Who am I?
* #version 2.0.0
*/
"use strict";
//random requirements.
//I believe you don't have to document these.
let cheerio = require('cheerio');
//constants to be documented.
//I usually use the #const, #readonly and #default tags for them
const CONST_1 = "1";
const CONST_2 = 2;
//An example class
class MyClass {
//the class constructor
constructor(config) {
//class members. Should be private.
this.member1 = config;
this.member2 = "bananas";
}
//A normal method, public
methodOne() {
console.log( methodThree("I like bananas"));
}
//Another method. Receives a Fruit object parameter, public
methodTwo(fruit) {
return "he likes " + fruit.name;
}
//private method
methodThree(str) {
return "I think " + str;
}
}
module.exports = MyClass;
Question
Given this mini class example above, how would you go about documenting it using JSDoc?
An example will be appreciated.

Late answer, but since I came across this googling something else I thought I'd have a crack at it.
You've probably found by now that the JSDoc site has decent explanations and examples on how to document ES6 features.
Given that, here's how I would document your example:
/**
* module description
* #module MyClass
*/
//constants to be documented.
//I usually use the #const, #readonly and #default tags for them
/** #const {String} [description] */
const CONST_1 = "1";
/** #const {Number} [description] */
const CONST_2 = 2;
//An example class
/** MyClass description */
class MyClass {
//the class constructor
/**
* constructor description
* #param {[type]} config [description]
*/
constructor(config) {
//class members. Should be private.
/** #private */
this.member1 = config;
/** #private */
this.member2 = "bananas";
}
//A normal method, public
/** methodOne description */
methodOne() {
console.log( methodThree("I like bananas"));
}
//Another method. Receives a Fruit object parameter, public
/**
* methodTwo description
* #param {Object} fruit [description]
* #param {String} fruit.name [description]
* #return {String} [description]
*/
methodTwo(fruit) {
return "he likes " + fruit.name;
}
//private method
/**
* methodThree description
* #private
* #param {String} str [description]
* #return {String} [description]
*/
methodThree(str) {
return "I think " + str;
}
}
module.exports = MyClass;
Note that #const implies readonly and default automatically. JSDoc will pick up the export, the #class and the #constructor correctly, so only the oddities like private members need to be specified.

For anyone visiting this question in 2019:
The answer given by #FredStark is still correct, however, the following points should be noted:
Most/all of the links in this page are dead. For the documentation of the JSDoc, you can see here.
In many IDEs or code editors (such as VSCode), you will find auto-completions such as #class or #constructor which are not necessary for the case of ES6 classes since these editors will recognize the constructor after the new keyword.

Related

How to annotate #attributes in google-closure interfaces

How can I annotate the interface of a JSON-response in google closure?
I have to use a JSONP interface which actually transforms some XML into JSON and provides it as a parameter to my callback. But unfortunately the origin XML contains some attributes so I get a JSON-Object with #attributes-fields e.g.
{
"output": {
"foo": "bar"
},
"#attributes": {
"baz": "attr"
}
}
I created an google-closure interface so the compiler will not minify my fields by accident and I get the neat auto-complition in my IDE.
/**
* #interface
*/
var JsonResult = function() {};
/**
* #type {JsonResultOutput}
*/
JsonResult.prototype.output;
/**
* #type {JsonResultAttributes}
*/
JsonResult.prototype['#attributes'];
/**
* #interface
*/
var JsonResultOutput = function() {};
/**
* #type {string}
*/
JsonResultOutput.prototype.foo;
/**
* #interface
*/
var JsonResultAttributes = function() {};
/**
* #type {string}
*/
JsonResultAttributes.prototype.baz;
Unfortunetly the compiler fires a warning if I try to annotate fields in brackets and strings. So my question is now: How should I annotate this to remove the warning? Maybe I can just remove this field in the interface, due to the problem that I have to write this field in the same way in the code as well, so the compiler will never minify this field. But I also want to document the object in it's full structure.
This looks like a bug to me. Feel free to file an issue at https://github.com/google/closure-compiler
For a workaround, you'll have to use object literal keys:
JsonResult.prototype = {
/**
* #type {JsonResultAttributes}
*/
'#attributes': {}
};

How to document a self-defined class so that this class can be used with #type in javascript

How to document a self-defined class so that this class can be used with #type in javascript in NetBeans IDE which supports JSDoc in version 2, ScriptDoc and ExtDoc.
So, let me make a example to make a question clear. Basically, I have a class named "Person" which looks like this:
/** #namespace */
classes = {
/**
* #constructor
* #param {string} name The name of person.'
*/
Person: function(name) {
/** #description Name of the person. */
this.personName = name;
}
};
I have another function will create a person with a name of something.
/** #return {classes.Person} something */
var getSomething = function() {
return new classes.Person("something");
};
When I type getSomething(), NetBeans IDE will realize which function I am trying to use. It will also tell me getSomething() will return a object of type classes.Person. However, when I put a dot after it, like
getSomething().
It do not give me the hint of member personName which means it do not recognize the return type of getSomething is a instance of class classes.Person. However, if I do like this:
new classes.Person().
It will give me the hint of member personName.
Are there any way to let NetBeans IDE realize it?

How do I document NodeJS native (V8) modules?

I have developed a native NodeJS module (using the NAN helpers). Now I am wondering what is the best way to document it.
The methods the module exports exist only in the C++ source code, however I wish to export Javascript documentation.
EDIT: I found another way that I think is better:
All JSDoc needs is to be able to attach the doclet to SOMETHING, so you can actually just do this (if you ignore JSHint warning about expecting an assignment or call instead of expression):
var nativeStuff = require('some/native/stuff');
/**
* My Cool Class
* #class
*/
nativeStuff.MyCoolClass;
/**
* My Cool Method
* #function
* #param {String} [name] The argument
*/
nativeStuff.MyCoolClass.prototype.CoolMethod;
/**
* Some Other Value
* #type {String}
*/
nativeStuff.someStringValue;
module.exports = nativeStuff;
This has the advantage of working with IDE's (at least WebStorm) and not requiring you to copy or proxy the object itself. Note though that you have to explicitly tell it what kind of field each entry is (with #function or #class or #type) because it can't infer it automatically otherwise.
Original Answer
There are a couple ways I know of, though I admit none seem particularly elegant.
In the small adapter file where you require() the native parts of the code and make it available as a module, you can assign each component individually and document them that way:
var nativeStuff = require('some/native/stuff');
// If your module only has one thing
/**
* My Cool Class
* #class MyCoolClass
*/
module.exports = nativeStuff;
// If it has several things
module.exports = {
/**
* My cool class
* #class
*/
MyCoolClass: nativeStuff.MyCoolClass,
/**
* My Other Cool Member
*/
OtherCoolMember: nativeStuff.OtherCoolMember
};
You could document members of the class this way too if you want to pick apart the class and re-assemble it, but it gets kinda unwieldy the deeper you go.
The other way I know of is to wrap every class method in native JS, which comes with a (almost negligible) performance hit:
var nativeStuff = require('some/native/stuff');
/**
* My Cool Class
*/
class MyCoolClass {
constructor() {
this._nativeObj = new nativeStuff.MyCoolClass();
}
/**
* Some Cool Method
* #param {String} [name] My name
*/
coolMethod(name) {
return this._nativeObj(name);
}
}
module.exports = MyCoolClass;
(Note this also works in older JS versions, but ES6 classes make stuff way easier to understand visually :)
You also can try using the #typedef directive to define things since a doclet about a typedef can be separate from the object it describes, but I don't think typedef's can document methods or classes in general, they're just for data objects.
I had to create a simple documentation generator to scan comments in source code in Javadoc-like style: https://github.com/aspectron/gendoc
Here is a part of such documentation, that looks like this:
/**
#module crypto
**/
/**
#class Hash
Hash generator
#function Hash(algorithm)
#param algorithm {String}
Constructor. Initiaize hash generator with specified algorithm, see #getHashes
Throws exception on unknown algorithm
**/
v8pp::class_<hash_generator> hash_class(bindings.isolate(), v8pp::v8_args_ctor);
hash_class
/**
#function reset([algorithm])
#param [algorithm] {String}
#return {Hash}
Reset hash generator to initial state optionaly changing generator algorithm.
Throws exception on unknown algorithm.
**/
.set("reset", &hash_generator::reset_v8)
...
Finally I opted for a not very elegant solution. I have created a separate JavaScript file which only has methods that are exported by my native API.
This file looks like this:
/** #namespace AwesomeLibrary
*
* #description API overview
*/
AwesomeLibrary = {
/**
* #param {string} param Input parameter
* #return combobulates {#link param}
*/
combobulate: function (param) {}
}
Then I am using JsDoc to generate the documentation of the project and passing this JavaScript file as an input rather than my native code. Finally I bundle the documentation with the binary distribution of my module.
This solution is not ideal as the documentation and the source code have to be maintained separately, however it has the advantage of zero overhead and a (rather) clean file. I have also disabled the source code generation in JsDoc as this would be obviously quite useless and only show the empty stubs.

JSDoc links to callback function

I have decided to use JSDoc to document a project I am working on. While reading the usage guide and questions here I still feel that I am not grasping some of the core concepts of JSDoc and I illustrated my incompetence in the following example: http://jsfiddle.net/zsbtykpv/
/**
* #module testModule
*/
/**
* #constructor
*/
var Test = function() {
/**
* #callback myCallback
* #param {Object} data An object that contains important data.
*/
/**
* A method that does something async
* #param {myCallback} cb a callback function
* #return {boolean} always returns true
*/
this.method = function(cb) {
doSomethingAsync(function(data) {
cb(data);
});
return true;
}
}
module.exports = Test;
Here, I have defined a module, indicated a constructor, and documented a method that takes a callback as one of its' parameters. Sounds pretty simple and appears to follow the guidelines set by the usage guide http://usejsdoc.org/.
But for some reason beyond my understanding (and that's probably the core concept I'm not getting), it shows the callback myCallback as a member of the testModule instead of the Test class. Shouldn't it default to be a member of the class and not the module? This also appears to prevent JSDoc from making a link to the callback definition, which is not a lot of fun.
Now I realize that if I were to write:
/**
* #callback module:testModule~Test~myCallback
* #param {Object} data An object that contains important data.
*/
/**
* A method that does something async
* #param {module:testModule~Test~myCallback} cb a callback function
* #return {boolean} always returns true
*/
I would get my desired behavior. But this seems to be a very clunky way of doing things and the generated links are far from pretty.
Sorry for the long buildup and thank you in advance for your help in my documentation effort :)
I have come across much the same problem. If you want nicer-looking links, you can always add a {#link} in the description and just use the canonical name in the #type like this:
/**
* #callback module:testModule~Test~myCallback
* #param {Object} data An object that contains important data.
*/
/**
* #param {myCallback} cb {#link module:testModule~Test~myCallback|myCallback}: a callback function
* #return {boolean} always returns true
*/
I realize that's a bit more frustrating to type, but it documents myCallback as a member of the class rather than the module, and the link looks nice.
If you really want the link in the #type and you don't care about how it documents the callback, you could also do this, which is a little less verbose (and what I've decided to do for my project):
/**
* #callback myCallback
* #param {Object} data An object that contains important data.
*/
/**
* #param {module:testModule~myCallback} cb a callback function
* #return {boolean} always returns true
*/
That will properly link to myCallback and document it as a member of the module.

How to include an already documented method in jsdoc-toolkit?

I have a JavaScript singleton object created with closure method:
/**
* This is the singleton.
*
* #namespace window.Something.Singleton
*/
window.Something.Singleton = (function() {
/**
* Foo method.
*
* #return {String} this method always returns with <code>bar</code>
*/
function _foo() { return "bar"; }
/**
* #lends window.Something.Singleton#
*/
return {
/**
* #borrows window.Something-_foo
* #function
*/
foo: _foo
};
}());
But the jsdoc-toolkit does not generate the inherited documentation from _foo method to the foo method what I would like to have.
If I write #see instead of #borrows it works (inserts a link to the correct method), but I don't want to copy&paste the documentation for the foo method to have a public documentation as well.
I did some tests, and I have good news and bad news :). The good news is that it looks like you can get this to work by putting the #borrows tag in the Singleton doc comment:
/**
* This is the singleton.
*
* #namespace Something.Singleton
* #borrows Something.Singleton-_foo as foo
*/
Something.Singleton = (function() {
// etc
})());
But this has several ramifications, good and bad:
The foo function is marked static. This is probably a good thing, as it seems to be accurate as I understand your code.
With the code as it is currently shown (i.e. no more methods on the singleton, etc), you can dispense with the #lends tag entirely, unless you want to include it for clarity. If all methods are listed as #borrows on the top singleton namespace, then you don't need to further document them in the returned object. Again, this is probably a good thing.
The bad news is that I couldn't get this to work unless the borrowed method was explicitly marked #public - which makes it show up, redundantly, in the documentation. I think this is unavoidable - if jsdoc-toolkit thinks the method is private, it won't create documentation, so you can't refer to it (I get WARNING: Can't borrow undocumented Something.Singleton-_foo.). If the method is public, it gets displayed in the documentation.
So this works:
/**
* This is the singleton.
*
* #namespace Something.Singleton
* #borrows Something.Singleton-_foo as foo
*/
Something.Singleton = (function() {
/**
* #public
* Foo method.
*
* #return {String} this method always returns with <code>bar</code>
*/
function _foo() { return "bar"; }
return {
foo: _foo
};
}());
...in that it copies the documentation for _foo to foo, but it will display _foo in the documentation page as well:
Method Summary
<inner> _foo()
<static> Something.Singleton.foo()
Probably the best workaround is simply to forget #borrows entirely and explicitly name _foo as Something.Singleton.foo in the doc comment, marking it as a public function (you could dispense with #public if you didn't name your inner function with an underscore, but this tells jsdoc-toolkit to treat it as private unless told otherwise):
/**
* This is the singleton.
*
* #namespace Something.Singleton
*/
Something.Singleton = (function() {
/**
* #name Something.Singleton#foo
* #public
* #function
* Foo method.
*
* #return {String} this method always returns with <code>bar</code>
*/
function _foo() { return "bar"; }
return {
foo: _foo
};
}());
This will produce the code documentation you're looking for, and puts the comment next to the actual code it relates to. It doesn't fully satisfy one's need to have the computer do all the work - you have to be very explicit in the comment - but I think it's just as clear, if not more so, than what you had originally, and I don't think it's much more maintenance (even in your original example, you'd have to change all your doc comments if you renamed Something.Singleton).
http://code.google.com/p/jsdoc-toolkit/wiki/TagBorrows
#borrows otherMemberName as thisMemberName
otherMemberName - Required: the namepath to the other member.
thisMemberName - Required: the new name that the member is being assigned to in this class.
/** #constructor */
function Remote() {
}
/** Connect to a remote address. */
Remote.prototype.transfer = function(address, data) {
}
/**
* #constructor
* #borrows Remote#transfer as this.send
*/
function SpecialWriter() {
this.send = Remote.prototype.transfer;
}
Any documentation for Remote#transfer will also appear as documentation for SpecialWriter#send.

Categories