JSDoc文件可以动态生成方法吗?

kdb*_*man 5 javascript jsdoc

这是一个构造函数A,它给出了实例2的方法:printThingprintBall.我使用JSDoc来记录这样的方法:

var A = function () {

    /**
     * Prints 'Thing'
     * @param {Number} N - The number of times to print.
     */
    this.printThing = function (N) {
        var i = 0;
        while (i < N) {
            console.log('Thing');
            i++
        }
    };

    /**
     * Prints 'Ball'
     * @param {Number} N - The number of times to print.
     */
    this.printBall = function (N) {
        var i = 0;
        while (i < N) {
            console.log('Ball');
            i++
        }
    };

};
Run Code Online (Sandbox Code Playgroud)

这是一个等效的构造函数,它动态生成相同的方法,如下所示:

var A = function () {

    var me = this;
    var registerPrinter = function (name) {
        me['print' + name] = function (N) {
            var i = 0;
            while (i < N) {
                console.log(name);
                i++;
            }
        };
    };

    registerPrinter('Thing');
    registerPrinter('Ball');
}
Run Code Online (Sandbox Code Playgroud)

两个构造函数生成的实例的行为是相同的:

> var a = new A();
> a.printBall(4);
Ball
Ball
Ball
Ball
Run Code Online (Sandbox Code Playgroud)

如何使用JSDoc来记录第二个A构造函数中生成的方法?


编辑:registerPrinter在构造函数的范围内是私有的.它可以(并且应该)记录,但它只是在内部使用.这个问题是关于记录A实例的结果公共接口.

Pet*_*ter 6

@name 是为此而做的:

对于在代码中不易看到的符号,此标记最适用于"虚拟注释"...

ES6:

/** Class A */
class A {
    constructor () {
        ['Thing', 'Ball'].map((name) => {
            this['print' + name] = (N) => {
                let i = 0;
                while (i < N) {
                    console.log(name);
                    i++;
                }
            };
        });
    }
}

/**
 * @name A#printThing
 * @function
 * @memberof A
 * @description Prints 'Thing'
 * @param {Number} N - The number of times to print.
 */

/**
 * @name A#printBall
 * @function
 * @memberof A
 * @description Prints 'Ball'
 * @param {Number} N - The number of times to print.
 */
Run Code Online (Sandbox Code Playgroud)

ES5:

/**
 * @class A
 */
var A = function () {

    var me = this;
    var registerPrinter = function (name) {
        me['print' + name] = function (N) {
            var i = 0;
            while (i < N) {
                console.log(name);
                i++;
            }
        };
    };

    ['Thing', 'Ball'].map(registerPrinter);

    /**
     * @name A#printThing
     * @function
     * @memberof A
     * @description Prints 'Thing'
     * @param {Number} N - The number of times to print.
     */

    /**
     * @name A#printBall
     * @function
     * @memberof A
     * @description Prints 'Ball'
     * @param {Number} N - The number of times to print.
     */
}
Run Code Online (Sandbox Code Playgroud)