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

前端 未结 5 1277
时光取名叫无心
时光取名叫无心 2020-11-30 08:57

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.metho         


        
5条回答
  •  野性不改
    2020-11-30 09:30

    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.

提交回复
热议问题