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.
Related
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.
I am trying to use JsDoc to document es6 classes. Can't believe that you can't pass a class as a parameter (a class type, not an instance type).
I've been trying things but can't get this simple code to work so that JsDoc doesn't throw me some warnings.
I can't get it to work unless I create a #typedef for each of my classes, then add manually all own and inherited members to it. Can't even do a mixin!
Has anyone succeeded in passing a constructor/class parameter? So that JsDoc be in the static context, not the instance context?
/**
* #class A
*/
class A {
/**
* #static
*/
static helloFromClassA(){
}
}
/**
* #class B
* #extends A
*/
class B extends A{
/**
* #static
*/
static helloFromClassB(){
}
}
/**
* Class as object
* #param {A} ClassArgument
*/
function fn1(ClassArgument){
ClassArgument.helloFromClassA(); // Unresolved function or method helloFromClassA
// Does not work because ClassArgument is interpreted as an
// instance of A, not A's constructor
}
/**
* // Class as function
* #param {Function} ClassArgument
*/
function fn2(ClassArgument){
ClassArgument.helloFromClassA(); // Unresolved function or method helloFromClassA
// Does not work because ClassArgument is interpreted as an
// empty function, not A's constructor
}
/**
* // Type definition
* #typedef {Object} AClass
* #property {Function} helloFromClassA
* #property {Function} super
*/
/**
* // Trying to mixin the AClass
* #typedef {Object} BClass
* #property {Function} helloFromClassB
* #mixes {AClass}
* #mixes {A}
*/
/**
* // Adding manually all members
* #typedef {Object} BClass2
* #property {Function} helloFromClassB
* #property {Function} helloFromClassA
*/
/**
* #param {BClass} ClassArgument
*/
function fn3(ClassArgument){
ClassArgument.helloFromClassA(); // Unresolved function or method helloFromClassA
// Does not work because the BClass typedef does not take
// into account the mixin from AClass, nor from A
ClassArgument.helloFromClassB(); // No warming
}
/**
* #param {BClass2} ClassArgument
*/
function fn4(ClassArgument){
ClassArgument.helloFromClassA(); // No Warning
ClassArgument.helloFromClassB(); // No warming
// Works because we manually defined the typedef with all own
// and inherited properties. It's a drag.
}
fn1(B);
fn2(B);
fn3(B);
fn4(B);
jsDoc issue : https://github.com/jsdoc3/jsdoc/issues/1088
I've been running into same issue with auto-completion in WebStorm multiple times. While it looks like currently there is no straight-forward way in jsdoc to say that parameter is a reference to a constructor (not to an instance), there is a suggestion from JetBrains team to implement something like #param {typeof Constructor} (where typeof is from typescript) or #param {Constructor.} that was suggested by closure compiler team. You can vote for following issue to get your main concern with WebStorm autocompletion resolved - https://youtrack.jetbrains.com/issue/WEB-17325
In Visual Studio Code, you can specify
#param {function(new:MyClass, SomeArgType, SecondArgType, etc...)}
I'm not sure what spec that syntax comes from or who else supports it, but it Works For Me.
typescript and google closure both support {typeof SomeClass} for referencing a class as a type (not a class instance). Unfortunately jsdoc doesn't support that syntax and will fail to compile it (https://github.com/jsdoc3/jsdoc/issues/1349).
Because I want to type-checking my JavaScript with typescript and also want to generate documentation I made this jsdoc plugin to transform expressions like {typeof SomeClass} into {Class<SomeClass>} so I can have both things: https://github.com/cancerberoSgx/jsdoc-typeof-plugin
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.
I compile my source with closure compiler and when i call a function that got an event object from network the application throws an error in console.
The function called is:
/**
* #param {goog.events.Event} event Socket.io-Wrapper Event.
*/
de.my.app.admin.prototype.onSaved = function(event){
var category = event.data[0].category; //<-- here it throws the error because category get compiled.
var id = event.data[0].id;
var oldid = event.data[0].oldid;
[...]
}
the event object looks like this
{ data:{
0: {
category: 'someString',
id: 5,
oldid: -5
} }
[...someMoreValuesAddedBySocketIO...]
}
that is the behavior i expected.
now i add an externs declaration like this to my externs file but i didn't alter the type declaration of the #param at the function and the error disappears:
var xterns;
/**
* #typedef {{
* category : string,
* oldid : number,
* id : number
* }}
*/
xterns.NOTUSEDNAME;
/**
* #type {string}
*/
xterns.NOTUSEDNAME.prototype.category;
/**
* #type {number}
*/
xterns.NOTUSEDNAME.prototype.oldid;
/**
* #type {number}
*/
xterns.NOTUSEDNAME.prototype.id;
In short: I have a #param {goog.events.Event} event declaration and an extern for xterns.NOTUSEDNAME solves the compiler problems...
Can anyone explain why this happens?
This is a common misconception. Closure-compiler will not rename a property if any extern object contains a property of the same name. See the FAQ. If the type based optimizations are enabled, then this is no longer true and I would expect your code to break again.
To make this code type safe and compile without warnings, you would need to either:
Reference the data properties using quoted syntax event.data[0]['category']. Your properties will never be renamed by the compiler using this method (which is often used by JSON Data).
Extend the goog.events.Event type with a custom object that defines the data object as a strongly typed array.
Example:
/**
* #constructor
* #extends {goog.events.Event}
*/
de.my.app.AdminEvent = function() {};
goog.inherits(de.my.app.AdminEvent, goog.events.Event);
/** #type {Array.<{category:string, id:number, oldid:number}>} */
de.my.app.AdminEvent.prototype.data = [];
Depending on your exact situation, an interface might be a better option.
I'm creating an AngularJS service to validate form inputs and I can't for the life of me figure out how to use JSDoc3 to create reasonable documentation.
Ideally I need to export the documentation for the validator service as well as the documentation for each validator (internal objects)
After googling around a bit I was able to get it kind of working by hacking around a bit with namespaces, but I'm wondering if there's a right way to do this. A way that won't muck up somebody else's JSDoc if they include my service.
Example:
angular.module('services.utility')
.factory('validator', [function () {
var validators = {
/**
* Requires a field to have something in it.
* #param {String|Boolean} val The value to be checked.
* #return {Object}
*/
'required': function(val){
// check against validator
return {'valid': true, 'msg': 'passed!'};
},
/**
* Requires a field to be less than a number.
* #param {Number} val The value to be checked.
* #param {Number} check The value to be checked against.
* #return {Object}
*/
'lessThan': function(val){
// check against validator
return {'valid': true, 'msg': 'passed!'};
}
};
return {
/**
* This is the main validation routine.
* #param {Object} vObjs An object to be processed.
* #return {Boolean}
*/
'validate': function(thingsToValidate){
// run some validations from the validators
// and return a bool.
}
};
}]);
In a perfect world, modifications to the above would let me generate a nice, non-global, JSDoc hierarchy where a user could read about how to use the validator as a whole, or dive in and look what needed to be passed in for each type of validation.
Thanks so much for any help you can give!
The way my team works is that we actually only document the actual factory function as if the user were going to read it. You've actually skipped over that guy. Either way, you can treat that as the entry point for your documentation and combine it with your "method" documentation for the full picture. You could make use of the #namespace documentation in combination with this.
/** Here is how you use my factory. #param #return */
my.validator.factory = function() { return { validate: function(){} }; }
/** Here are some validators. #enum {Function(*):ValidationResult} **/
my.validator.Validators = {}
module.factory('validator', my.validator.factory);
Depending on what you really want, you may prefer to use a prototype. That's where documentation can really shine:
/** Here is how you use my factory. #param #return #constructor */
my.Validator = function() {}
/** My validation function. #param #return */
my.Validator.prototype.validate = function() {}
/** Here are some validators. #enum {Function(*):ValidationResult} **/
my.Validator.Validators = {}
module.service('validator', my.Validator);
Using the prototype with your documentation really sticks it all together for me. It's like documenting your validator as one class entity, which makes the most sense to me.