英文:
How do I get the JSDoc text (docstring) from a function inside the code in JavaScript?
问题
<span>
代表一本书。
@constructor
</span>
英文:
Considering I have a simple function, I want to extract the JSDoc string inside the code and display it in the page, like so:
/**
* Represents a book.
* @constructor
*/
function Book(title, author) {
// contents
}
<span>
Represents a book.
@constructor
</span>
Can this be done?
答案1
得分: 1
In JavaScript, comments are not a part of the function's AST (Abstract Syntax Tree), they're purely metadata and most JavaScript engines don't preserve them when the function is converted to a string.
如果不是这样的话,以下代码将会生效:
function extractJSDoc(func) {
var match = func.toString().match(/\/\*\*([\s\S]*?)\*\//);
return (match && match.length > 1) ? match[1].trim() : '';
}
/**
* Represents a book.
* @constructor
*/
function Book(title, author) {
// contents
}
document.getElementById("displayJSDoc").innerText = extractJSDoc(Book);
作为替代方案,您可以考虑将您的JSDoc注释存储在一个单独的数据结构或文件中,以便在需要时访问。另一种可能的方法是利用构建工具或转译器(如Babel)在构建步骤中提取注释并生成单独的文档文件,或者将它们注入到您需要的代码中。
英文:
In JavaScript, comments are not a part of the function's AST (Abstract Syntax Tree), they're purely metadata and most JavaScript engines don't preserve them when the function is converted to a string.
If that was not the case, the following could would work:
function extractJSDoc(func) {
var match = func.toString().match(/\/\*\*([\s\S]*?)\*\//);
return (match && match.length > 1) ? match[1].trim() : '';
}
/**
* Represents a book.
* @constructor
*/
function Book(title, author) {
// contents
}
document.getElementById("displayJSDoc").innerText = extractJSDoc(Book);
<span id="displayJSDoc"></span>
As an alternative, you could consider storing your JSDoc comments in a separate data structure or file which you can access when needed. Another possible approach is to make use of a build tool or transpiler (like Babel) to extract the comments during a build step and generate a separate documentation file or inject them into your code where needed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论