Difference in listing variables in JavaScript [duplicate]

陌路散爱 提交于 2021-01-28 05:37:09

问题


Possible Duplicate:
Declaring Multiple Variables in JavaScript

I was wondering whether there is a difference in listing variables in JavaScript (and JS libraries).

Example:

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

OR

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

I always thought that the difference only lies in notation. The first example is shorter and possibly faster to execute. Recently I did some testing and now I am not sure anymore. Can anyone clear this up?

Is there a difference in execution speed, result, method?


回答1:


I broke the habit of using multiple var statements when I started using jsLint. It always caught that and said that it was faster to separate by a comma.

Looking into this more, there seem to be many sources that agree with this.

From jsLint #scope

It is recommended that a single var statement be used per function.

From A List Apart:

The var statement defines one or more variables. Sometimes you’ll see code that looks like this:

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




回答2:


That's not jQuery that just plain-jane JavaScript variable declaration.

As far as a difference, there isn't one. The only speed increase you could acquire would be to stop spinning up multiple jQuery objects and re-reference existing ones for further processing. e.g.

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

See also JavaScript variable definition: Commas vs. Semicolons



来源:https://stackoverflow.com/questions/13270724/difference-in-listing-variables-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!