Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

What is the advantage of initializing multiple javascript variables with the same var keyword?

When I read javascript code that is clean and written by people who are obviously very good at it, I often see this pattern

var x = some.initialization.method(),
    y = something.els(),
    z;

What is the advantage of that over writing

var x = some.initialization.method();
var y = something.els();
var z;

The second format is easier to maintain, since each line exists by itself. So you can erase a line or add a line, and not have to look around to see if it's the first or last variable to be initialized. This also means source control diffs/merges will work better. Given these disadvantages, I'm guessing there's some advantage to the first format -- but what is it? Surely they execute identically because it's the same to the parser.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's a slight advantage with the size of the javascript that is sent to the browser; Google's Closure compiler in 'whitespace only' mode will compile the single var version into:

var x=some.initialization.method(),y=something.els(),z;

and the multi as:

var x=some.initialization.method();var y=something.els();var z;

I changed your else to els so that it would compile.

This isn't a massive gain (especially if you are also compressing the files), and the 'simple' compilation mode will do this for you anyway, so I probably wouldn't be too concerned about it unless you can find more compelling reasons.

One reason you may not want to do this is that if you accidentally use a semicolon instead of a comma you've just found a global.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...