AlexAtNet AlexAtNet - 1 month ago 26
Javascript Question

Describe property defined with Object.defineProperty

I want to add JSDoc documentation for the property added as

Object.defineProperty
. I guess that something like this might work:

/** @constructor */
function MyClass() {
/** @property {Number} rnd */
Object.defineProperty(this, 'rnd', {
get : function () { return Math.random(); }
});
}


But the generated JSDoc explanation does not have this property:

$ jsdoc -X test.js
[
{
"comment": "/** @constructor */",
"meta": {
"range": [ 20, 167 ],
"filename": "test.js",
"lineno": 2,
"path": "/jsdoctest",
"code": {
"id": "astnode100000001",
"name": "MyClass",
"type": "FunctionDeclaration",
"paramnames": []
},
"vars": { "": null }
},
"kind": "class",
"name": "MyClass",
"longname": "MyClass",
"scope": "global"
},
{
"comment": "",
"meta": {
"range": [ 116, 159 ],
"filename": "test.js",
"lineno": 5,
"path": "/jsdoctest",
"code": {
"id": "astnode100000012",
"name": "get",
"type": "FunctionExpression",
"value": "function"
}
},
"undocumented": true,
"name": "get",
"longname": "get",
"kind": "function",
"scope": "global"
},
{
"kind": "package",
"longname": "package:undefined",
"files": [ "/jsdoctest/test.js" ]
}
]


What will be the most appropriate approach to document this kind of properties? (Plugin maybe?)

Answer Source

This would do it:

/** @constructor */
function MyClass() {
  /**
   * @property {Number}
   * @name MyClass#rnd
   */
  Object.defineProperty(this, 'rnd', {
    get : function () { return Math.random(); }
  });
}

I've used the @property {type} name syntax but never inside of a class. What I typically do is something like:

/** @property {object} */
this.foo = {};

And then jsdoc uses this.foo to compute the name (foo) and which entity it belongs to. It appears that using @property {type} name in a class does not work.

If you specify the name with @name, then it knows what name to give to it and where it belongs. The # indicates that it is an instance variable (rather than static or inner). See the namepath documentation for details.