开发者

Commenting JavaScript functions á la Python Docstrings

开发者 https://www.devze.com 2022-12-11 10:58 出处:网络
It is valid JavaScript to write something like this: function example(x) { \"Here is a short doc what I do.\";

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 wirit开发者_开发百科ing 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消