1

可能重复:
在 JavaScript 中声明多个变量

我想知道在 JavaScript(和 JS 库)中列出变量是否有区别。

示例

var $this = $(this),
    $body = $("body"),
    $main-wrap = $("body > section.wrapper");

或者

var $this = $(this);
var $body = $("body");
var $main-wrap = $("body > section.wrapper");

我一直认为区别只在于符号。第一个示例更短,执行起来可能更快。最近我做了一些测试,现在我不确定了。任何人都可以清除这个吗?

执行速度、结果、方法有区别吗?

4

2 回答 2

4

那不是 jQuery,它只是简单的 JavaScript 变量声明。

就区别而言,没有一个。您可以获得的唯一速度提升是停止旋转多个 jQuery 对象并重新引用现有对象以进行进一步处理。例如

var body = $('body'),
    wrapper = body.children('section.wrapper');

另请参阅JavaScript 变量定义:逗号与分号

于 2012-11-07T13:25:48.880 回答
0

当我开始使用jsLint时,我打破了使用多个var语句的习惯。它总是抓住这一点,并说用逗号分隔会更快。

对此进行更多研究,似乎有很多消息来源同意这一点。

来自jsLint #scope

建议每个函数使用单个 var 语句。

列表分开

var 语句定义一个或多个变量。有时你会看到如下代码:

var image = document.getElementById("myImage");
var div = document.getElementById("myDiv");

This code defines two variables, one right after the other. I often see this pattern for 10 or more variables in a row. Doing so artificially inflates the size of your code because multiple var statements can be combined into one using a comma operator:

var image = document.getElementById("myImage"),
div = document.getElementById("myDiv"); 

This code also defines two variables and provides the same initialization. However, you’ve saved the three bytes that another var would have cost. Three bytes might not seem like a big deal, but if you’re able to find dozens of places where there’s currently an extra var statement, the savings can really add up.

However,

here are two fairly compelling reasons to use multiple var statements from SO posters. and here

于 2012-11-07T13:57:50.953 回答