如何记录使用Object.create创建的对象,该对象也具有原型方法

时间:2015-08-12 23:51:20

标签: javascript google-closure jsdoc jsdoc3

我正在尝试使用jsdoc3和闭包字典找出jsdoc的最佳方法。下面的代码几乎记录了我想要的内容,但@class标记在文档中添加了一个新关键字,我也对使用类定义感到不安,因为它不是真正的类。

/**
 * myObject constructor. <strong> Do not use with new.</strong>
 * @class myObject
 * @param {string} someText The text to store
 */
function myObject (someText) {  
  var instance = Object.create(myObject.prototype);  
  instance.someText = someText;

  return instance;
}

/**
 * Outputs to the console
 */
myObject.prototype.doSomething = function () {
  console.log(this.someText);
};

var test = myObject('foobar');
test.doSomething();

@namespace最初似乎是一个更好的选择,但它不允许在伪构造函数上记录@param或类似内容。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

这里演示了构造函数/工厂的可能实现,以及如何记录构造对象的成员:

/**
 * Constructs my object.
 *
 * <p>
 * It is not necessary to call this with <i>new</i> keyword.
 *
 * @name myObject
 * @namespace
 * @constructor
 * @param {string} someText The text to store
 */
function myObject ( someText ) {
    var instance = Object.create( myObject.prototype, {
        /**
         * A member, could be a value of any type.
         *
         * @type {string}
         * @memberof myObject#
         */
        anyMember: {
            value: "whatever"
        },
        /**
         * A <strong>method</strong> member.
         *
         * @param {string|number|object|function} anArgument A parameter.
         *
         * @method
         * @memberof myObject#
         */
        aMethodSpecially: {
            value: function ( anArgument ) {
                throw "Not yet implemented";
            }
        }
    } );

    /**
     * Some text.
     *
     * @property {string}
     */
    instance.someText = someText;

    return instance;
}

/**
 * Outputs to the console.
 *
 * @param {number|string|function|object} someArgument Some method argument.
 * @function doSomething
 * @memberof myObject#
 */
myObject.prototype.doSomething = function ( someArgument ) {
    // @ts-ignore
    console.log( this.someText );
};

var test = myObject( 'foobar' );
test.doSomething();

使用JSDoc 3生成的doc如下所示: enter image description here

---截图继续......

enter image description here

答案 1 :(得分:-1)

您尝试做的事似乎不必要地复杂化。如果您想要一个构造/返回特定类型的工厂方法,只需将其显式化:

/**
 * myObject factory.
 * @param {string} someText
 * @returns {!myObject} The constructed object.
 */
function createMyObject(someText) {  
  return new myObject(someText);
}

/*
 * @param {string} someText The text to store
 * @constructor
 */
function myObject (someText) {  
  this.someText = someText;
}

/**
 * Outputs to the console
 */
myObject.prototype.doSomething = function () {
  console.log(this.someText);
};

var test = createMyObject('foobar');
test.doSomething();