我一直在尝试使用 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");
}
}
但是在生成的 JSDoc 文档中找不到方法 greet
。我做错了什么?
最佳答案
不要那样添加原型(prototype)成员。那很奇怪/不好/错误。
您正在设置现有对象的整个 prototype
,而不是向其添加成员。这将导致性能问题、JS 引擎优化问题和意外行为。
如果您需要以某种方式覆盖原型(prototype),您应该使用 Object.setPrototypeOf()
方法。即使它是 native 方法,仍然不推荐使用。
如果您唯一的问题是“隐藏”一些私有(private)常量,您有以下选择:
- 使用 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;
})();
- 对私有(private)变量/常量使用传统的
_
前缀,并使用 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");
};
关于javascript - JSDoc - 如何记录原型(prototype)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27343152/