Documenting the return of a javascript constructor with jsdoc

[亡魂溺海] 提交于 2020-01-14 12:52:35

问题


I have a javascript function that returns a constructor (see code sample below). How would I document this with the @returns tag of jsdoc. It doesnt seem correct to do @returns {MyConstructor} because that implies I am returning an instance of "MyConstructor" rather than the constructor itself, right?

function MyConstructor() {
    var self = this;

    self.myFunction = function() {
        return true;
    };

    self.getMyFunctionResult = function() {
        return self.myFunction();
    };
}

/**
 * @returns {?} A constructor that will be instantiated
 */
function getConstructor() {
    return MyConstructor;
}

var constructor = getConstructor();
var instance = new constructor();

回答1:


You can check the types returned by your functions using:

console.log(typeof constructor, typeof instance); // function object

In the documentation it says:

/**
 * Returns the sum of a and b
 * @param {Number} a
 * @param {Number} b
 * @returns {Number} Sum of a and b
 */
function sum(a, b) {
    return a + b;
}

http://usejsdoc.org/tags-returns.html

So in you example it would be:

/**
 * Returns the MyConstructor class
 * @returns {Function} MyConstructor class
 */
function getConstructor() {
    return MyConstructor;
}

Or if you are creating an instance of an Item:

/**
 * Returns an instance of the MyConstructor class
 * @returns {Object} MyConstructor instance
 */
function getInstance() {
    return new MyConstructor();
}



回答2:


I do not think there is a way to use the brackets after @returns to document returning a specific instance. What goes in the brackets is interpreted as a type, always. This being said, there's a way to document that a specific instance of a type is being returned, by documenting the instance and using a link to the instance. I've shortened the code in the question to the essentials necessary to illustrate:

/**
 * @class
 */
function MyConstructor() {

}

/**
 * @returns {Function} A constructor that will be instantiated. Always
 * returns {@link MyConstructor}.
 */
function getConstructor() {
    return MyConstructor;
}

It can also be done with other things than classes:

/**
 * @public
 */
var foo = 1;

/**
 * @returns {number} {@link foo}.
 */
function getFoo(){
    return foo;
}

As far as I know, this is as good as it gets with jsdoc 3.




回答3:


Maybe little bit late, but I have problem to find proper answer for your question event today.

When I try generate JSDoc automatically on WebStorm, this is what I get:

class Test {}

/**
 *
 * @return {Test}
 * @constructor
 */
function getTestConstructor() {
    return Test;
}

Return type definition is still strange, but constructor annotation may fulfill the purpose.



来源:https://stackoverflow.com/questions/21002316/documenting-the-return-of-a-javascript-constructor-with-jsdoc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!