使用 jsdoc 记录 javascript 构造函数的返回

com*_*ius 5 javascript documentation jsdoc jscript jsdoc3

我有一个返回构造函数的 javascript 函数(请参阅下面的代码示例)。我将如何使用 jsdoc 的 @returns 标签来记录这一点。执行 @returns {MyConstructor} 似乎不正确,因为这意味着我返回的是“MyConstructor”的实例而不是构造函数本身,对吗?

function MyConstructor() {
    var self = this;

    self.myFunction = function() {
        return true;
    };

    self.getMyFunctionResult = function() {
        return self.myFunction();
    };
}

/**
 * @returns {?} A constructor that will be instantiated
 */
function getConstructor() {
    return MyConstructor;
}

var constructor = getConstructor();
var instance = new constructor();
Run Code Online (Sandbox Code Playgroud)

Kim*_*m T 2

您可以使用以下方法检查函数返回的类型:

console.log(typeof constructor, typeof instance); // function object
Run Code Online (Sandbox Code Playgroud)

在文档中它说:

/**
 * Returns the sum of a and b
 * @param {Number} a
 * @param {Number} b
 * @returns {Number} Sum of a and b
 */
function sum(a, b) {
    return a + b;
}
Run Code Online (Sandbox Code Playgroud)

http://usejsdoc.org/tags-returns.html

所以在你的例子中它将是:

/**
 * Returns the MyConstructor class
 * @returns {Function} MyConstructor class
 */
function getConstructor() {
    return MyConstructor;
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您正在创建 Item 的实例:

/**
 * Returns an instance of the MyConstructor class
 * @returns {Object} MyConstructor instance
 */
function getInstance() {
    return new MyConstructor();
}
Run Code Online (Sandbox Code Playgroud)