问题
I know that white space is irrelevant in JavaScript, but I am curious about style.
When defining a function like:
function Foo(a, b, c) {}
I do not put a space after the function name. But, if I am creating a function as an expression:
Bar(function (a, b, c) {
// do something
})
or
{
Foo: function (a, b, c) {
// do something
}
}
I find myself naturally typing a space. I think this is because I've trained myself to type a space immediately after the function keyword (or keywords in general). However, depending on the context, space can look awkward. What makes more sense? what do most people do?
Sorry if this has been asked before; I didn't see it come up.
回答1:
I do the same.
function () { ... }
function name() { ... }
It makes more sense to me this way. It is more readable with the space after the function
keyword (I do the same with if
, while
, etc) and it makes sense not to put it after the function name since you usually invoke it without a space.
回答2:
It is matter of personal preference. No doubt proper spacing does aid to readability which is always a good idea.
The important thing though when it comes to JavaScript coding style, is to always put starting curly brace on the same (due to automatic semi-colon insertion) line unlike:
function myFunc()
{
return
{
name: 'Jane'
};
}
var f = myFunc();
console.log(f); // undefined
Read More:
- Code Conventions for the JavaScript Programming Language
回答3:
I agree, when coding Javascript i want my code to be as readable as possible and I've gotten to find that having a whitespace to separate the the keyword ease the reading, for me.
回答4:
My suggestion:
If the ()
is the function invocation operator, don't put a space before it. In all other cases do put a space before it.
function f ( x ) {
// ...
}
var g = function ( y ) {
// ...
};
f( 1 );
g( 2 );
That way, you can identify invocation operators more easily.
来源:https://stackoverflow.com/questions/9300636/javascript-space-after-function