Domanda

Ho una funzione JavaScript che restituisce un costruttore (vedere il campione di codice sotto).Come documenterò questo con il tag @returns di JSDOC.Non sembra corretto fare @returns {myconstructor} perché ciò implica che sto restituendo un'istanza di "myconstructor" piuttosto che il costruttore stesso, giusto?

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();
.

È stato utile?

Soluzione

È possibile controllare i tipi restituiti dalle funzioni utilizzando:

console.log(typeof constructor, typeof instance); // function object
.

Nella documentazione dice:

/**
 * 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;
}
.

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

Così nell'esempio sarebbe:

/**
 * Returns the MyConstructor class
 * @returns {Function} MyConstructor class
 */
function getConstructor() {
    return MyConstructor;
}
.

o se stai creando un'istanza di un elemento:

/**
 * Returns an instance of the MyConstructor class
 * @returns {Object} MyConstructor instance
 */
function getInstance() {
    return new MyConstructor();
}
.

Altri suggerimenti

Non penso che ci sia un modo per utilizzare le staffe dopo @returns to Document Returning A specifico istanza.Ciò che va tra parentesi è interpretato come tipo , sempre.Detto questo, c'è un modo per documentare che un'istanza specifica di un tipo viene restituita, documentando l'istanza e utilizzando un collegamento all'istanza.Ho accorciato il codice nella domanda per gli elementi essenziali necessari per illustrare:

/**
 * @class
 */
function MyConstructor() {

}

/**
 * @returns {Function} A constructor that will be instantiated. Always
 * returns {@link MyConstructor}.
 */
function getConstructor() {
    return MyConstructor;
}
.

Può anche essere fatto con altre cose rispetto alle classi:

/**
 * @public
 */
var foo = 1;

/**
 * @returns {number} {@link foo}.
 */
function getFoo(){
    return foo;
}
.

Per quanto ne so, questo è buono come si ottiene con JSDoc 3.

Forse un po 'in ritardo, ma ho problemi a trovare una risposta corretta per il tuo evento di domanda oggi.

Quando provo generare automaticamente JSDoc su WebStorm, questo è ciò che ottengo:

class Test {}

/**
 *
 * @return {Test}
 * @constructor
 */
function getTestConstructor() {
    return Test;
}
.

La definizione del tipo di ritorno è ancora strano, ma l'annotazione del costruttore può soddisfare lo scopo.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top