JSDoc - 如何记录原型方法

Kub*_*lik 15 javascript documentation-generation code-documentation jsdoc jsdoc3

我一直在尝试使用JSDoc记录以下代码:

/**
 * @module person
 */

 /**
  * A human being.
  * @class
  * @param {string} name
  */
function Person(name){
    this.name = name
}

Person.prototype = new function(){
    var amount_of_limbs = 4;

    /**
     * Introduce yourself
     */
    this.greet = function(){
        alert("Hello, my name is " + this.name + " and I have " + amount_of_limbs + " limbs");
    }
}
Run Code Online (Sandbox Code Playgroud)

但是greet在最终的JSDoc文档中找不到该方法.我究竟做错了什么?

Onu*_*rım 12

不要添加这样的原型成员.这很奇怪/坏/错.

您正在设置整个prototype现有对象,而不是向其添加成员.这导致性能问题,JS引擎优化问题和意外行为.

如果你以某种方式需要覆盖原型,你应该使用Object.setPrototypeOf()方法.即使它是一种原生方法,仍然不推荐使用.

如果你唯一的问题是"隐藏"一些私有常量,你有以下选择:

  1. 使用IIFE(立即调用函数表达式):
/**
 * A human being.
 * @class
 */
var Person = (function () {

    // private variables
    var amountOfLimbs = 4;

    /**
     * Initializes a new instance of Person.
     * @constructs Person
     * @param {string} name
     */
    function Person(name) {
        /**
         * Name of the person.
         * @name Person#name
         * @type {String}
         */
        this.name = name
    }

    /**
     * Introduce yourself
     * @name Person#greet
     * @function
     */
    Person.prototype.greet = function () {
        alert("Hello, my name is " + this.name + " and I have " + amountOfLimbs + " limbs");
    };

    return Person;
})();
Run Code Online (Sandbox Code Playgroud)
  1. 使用_私有变量/常量的常规前缀并使用JSDoc @private标记.
/**
 * Person class.
 * @class
 */
function Person(name) {

    /**
     * Name of the person.
     * @name Person#name
     * @type {String}
     */
    this.name = name

    /**
     * Amount of limbs.
     * @private
     */
    this._amountOfLimbs = 4;
}

/**
 * Introduce yourself.
 * @name Person#greet
 * @function
 */
Person.prototype.greet = function () {
    alert("Hello, my name is " + this.name + " and I have " + this._amountOfLimbs + " limbs");
};
Run Code Online (Sandbox Code Playgroud)

  • @Onur Yıldırım 虽然您的回答是一个非常有趣的评论,但它没有回答 OP 问题,即“如何记录原型方法?” 如果你有这个问题的答案,请更新你的答案。我很想知道解决方案是什么。 (3认同)

flo*_*oww 5

根据https://github.com/jsdoc3/jsdoc/issues/596正确答案是:使用@memberof

 /**
  * A human being.
  * @class
  * @constructor
  * @param {string} name
  */
function Person(name) { /*...*/ }
Person.prototype = {};
Person.prototype.constructor = Person;

/**
 * Perform a greeting.
 * @memberof Person
 */
Person.prototype.greet = function () { /*...*/ }
Run Code Online (Sandbox Code Playgroud)


Kub*_*lik -3

事实证明我需要使用@alias关键字。http://usejsdoc.org/tags-alias.html