使用相同的var关键字初始化多个javascript变量有什么好处? [英] What is the advantage of initializing multiple javascript variables with the same var keyword?

查看:113
本文介绍了使用相同的var关键字初始化多个javascript变量有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我阅读那些显然非常擅长的javascript代码时,我常常看到这种模式

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;

写作的优势是什么

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.

推荐答案

发送的javascript大小略有优势到浏览器; Google的 Closure编译器在仅限空白模式下将单个var版本编译为:

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;

和multi as:

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

我将 else 更改为 els 以便它可以编译。

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.

这篇关于使用相同的var关键字初始化多个javascript变量有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆