gpt4 book ai didi

javascript - JSDoc 可以记录动态生成的方法吗?

转载 作者:行者123 更新时间:2023-12-04 18:03:56 25 4
gpt4 key购买 nike

这是一个构造函数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++
}
};

};

这是一个等效的构造函数,它动态生成相同的方法,如下所示:
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');
}

两个构造函数生成的实例的行为是相同的:
> var a = new A();
> a.printBall(4);
Ball
Ball
Ball
Ball

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

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

最佳答案

@name 为此:

This tag is best used in "virtual comments" for symbols that are not readily visible in the code...



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.
*/

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.
*/
}

关于javascript - JSDoc 可以记录动态生成的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36042060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com