注释 JavaScript 函数 á Python 文档字符串
编写如下内容是有效的 JavaScript:
function example(x) {
"Here is a short doc what I do.";
// code of the function
}
该字符串实际上不执行任何操作。有什么理由不应该以这种方式在 JavaScript 中注释他/她的函数吗?
在编写问题时我可以想到两点:
必须启动字符串文字,从长远来看这可能会代价高昂
字符串文字不会被 JS 压缩器识别为可移动
还有其他要点吗?
编辑:为什么我提出这个主题:我在 John Resig 的博客,其中新的 ECMA 5 标准使用未分配的字符串文字来启用“严格模式”。现在我的兴趣只是评估做这样的文档是否有用途或危险。
It is valid JavaScript to write something like this:
function example(x) {
"Here is a short doc what I do.";
// code of the function
}
The string actually does nothing. Is there any reason, why one shouldn't comment his/her functions in JavaScript in this way?
Two points I could think of during wiriting the question:
The string literal must be initiated, which could be costly in the long run
The string literal will not be recognized as removable by JS minifiers
Any other points?
Edit: Why I brought up this topic: I found something like this on John Resig's Blog, where the new ECMA 5 standard uses a not assigned string literal to enable "strict mode". Now it was my interest to just evaluate, if there could be uses or dangers in doing such documentation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Javascript 中这样做确实没有意义。在 Python 中,该字符串可用作函数、类或模块的 __doc__ 成员。因此,这些文档字符串可用于内省等。
如果您在 Javascript 中创建这样的字符串,那么与使用注释相比,您没有任何好处,而且还会有一些缺点,例如字符串始终存在。
There's really no point in doing this in Javascript. In Python, the string is made available as the
__doc__
member of the function, class, or module. So these docstrings are available for introspection, etc.If you create strings like this in Javascript, you get no benefit over using a comment, plus you get some disadvantages, like the string always being present.
我正在寻找一种将多行字符串添加到我的代码中而不用 \n 乱七八糟的方法。看起来这个模块符合要求:
https://github.com/monolithed/doc
不幸的是,评论赢了无法缩小,但我想您可以编写一个编译任务将文档字符串转换为“\n”格式。
I was looking for a way to add multi-line strings to my code without littering it with \n's. It looks like this module fits the bill:
https://github.com/monolithed/doc
Unfortunately, the comments won't survive minification, but I suppose you could write a compile task to convert docstrings to "\n" format.