Search code examples
javascriptdocumentationjscriptjsdocjsdoc3

Documenting the return of a javascript constructor with jsdoc


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();

Solution

  • 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();
    }