问题
In JavaScript, the standard rules for code formatting don't seem to cut it. You still end up with messes of });});
all over the place and I don't believe I even know of established rules for the correct indention of anonymous functions declared as arguments to other functions.
In short, I have trouble reading my own JavaScript, and I bet I'm not alone.
I think the idea that I am coming around to is to just not define functions within other functions. Write every function with a name and as a child to the script tag. When you need to pass functions around, use their names. Of course, this makes it a lot harder to use closures [edit: you cannot use closures at all if you write your code that way]. Also, this might cause problems with memory management?
Anyone else have thoughts on this?
回答1:
I bet you should just follow already established coding standards.
You may follow coding standard for one of two best JavaScript frameworks:
- Mootols (coding standard here), or
- jQuery (coding standard here),
Basically use tabs instead of spaces (this may be difficult for some, but I believe is established standard for JS), avoid unnecessary spaces (eg. in ) {
in function definition space is not welcome and should probably look like: ){
), etc.
PS. It is my personal > opinion < that MooTools & jQuery are 2 the best JS frameworks.
回答2:
You need to format your code in order to be readable. And always while typing JS use IDE features to format code and each new command put into new row. Then you won't have a problems.
You can use Online JavaScript beautifier for your existing javascript.
回答3:
http://en.wikipedia.org/wiki/Indent_style http://en.wikipedia.org/wiki/Coding_conventions
Are a good place to start. I personally use the K&R style for clarity. When it comes down to it though all you need to do is find a style you like and stick with it. Consistency ;]
来源:https://stackoverflow.com/questions/7987027/how-to-write-readable-javascript