JSDoc - 如何记录原型方法

2024-03-12

我一直在尝试使用 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");
    }
}

但方法greet在生成的 JSDoc 文档中找不到。我究竟做错了什么?


不要像这样添加原型成员。这很奇怪/不好/错误。

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

如果您需要以某种方式覆盖原型,您应该使用Object.setPrototypeOf()方法。尽管它是本机方法,但仍然不推荐。

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

  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;
})();
  1. 使用常规的_私有变量/常量的前缀并使用 JSDoc@private tag.
/**
 * 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");
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JSDoc - 如何记录原型方法 的相关文章