简体   繁体   中英

Javascript/jQuery variable, what is the proper way to use a var?

I am sorry if this is a dumb or easy question but I am fairly new to Javascript/jQuery. The past month I have really started to delve into the land of scripting and have seen two different, maybe three, ways people use var in Javascript/jQuery.

The way I use a var is like so,

var nav = $('nav');

nav.hide();

A very common way I have seen people use vars,

var nav = $('nav');

$(nav).hide();

From the answers,

var $nav = $('nav');

$nav.hide();

From what I have learned from searching through Google is what you typed inside the variable is saved there to later be used. I then figured if I wrote the $() around the var when I was using it, it would duplicate the $(). Yet both ways seem to work so I know it does not duplicate it and therefore can tell that it is the same thing.

Is there a correct way to use vars or are both equally the same and it doesn't matter?

I apologize again if this is a known answer and will be happy to remove it if someone can show me the original question but I couldn't find anything on it.

A great bit of information from an answer that I didn't mark as the answer but I find to be very important.

var element = document.createElement("div");
$("body").append(element);
$(element).hide(); 

In the example above, $(element) is necessary, because it takes a DOM object and converts it to a jQuery selector. jQuery functions only work on jQuery selectors, so you couldn't simply do element.hide().

$() creates a new jQuery object. If you save a jQuery object to a variable it is pointless to create another jQuery object from it, although it still works. You will often see people wrap variables that were previously created as jQuery objects in $() purely due to bad practice and either forgetting it's already an object...or not understanding what they just created in the first place

Perhaps you may have seen

var $nav = $('nav');

$nav.hide();

Using the $ prefix is a common practice to denote that the variable is a jQuery object for code readability mostly

Both variables store a jQuery object, which has access to jQuery methods. The latter approach unnecessarily tries to re-wrap that jQuery object in another jQuery object. The former approach is 'correct,' in that it's more efficient and less, to be frank, silly .

I've seen this issue in a lot of places. People use a lot of $ when they don't need to. Some use it just as an ornament on their variable name, which adds to the confusion.

First of all, there are no jQuery variables, only JavaScript variables, and as you said, variables store information. When the right hand side begins with $(), you're storing the results of a jQuery function in the variable. In the vast majority of cases, what you'll be storing is called a jQuery selector .

In the case of var nav = $('nav') , what you're storing is a selector representing all the elements in the DOM that are nav tags, ie that look like <nav></nav> (or equivalent).

As others already mentioned, the $(nav) is taking the stored selector, and creating a new selector out of it. It accomplishes nothing and is redundant, and is a poor programming practice, even if it is a pervasive one.

However, there is a similar syntax that makes sense:

var element = document.createElement("div");
$("body").append(element);
$(element).hide(); 

In the example above, $(element) is necessary, because it takes a DOM object and converts it to a jQuery selector. jQuery functions only work on jQuery selectors, so you couldn't simply do element.hide() .

As I mentioned at the top, some people also use $ as a decorator on their variable names, eg var $selector = $("nav") . The $ on the left hand side means nothing - it's just a character in a variable name, but they use it as a convention to remind themselves that they're storing a jQuery selector. I'd avoid it, simply because it adds to the confusion, but it's out there, so I just wanted to mention it.

var is used to create any kind of variable. Could be var diceRoll = 4 or var myMessage = "Hello!" , or anything else.

$ is a function that jQuery provides, which behaves in different ways depending on what you pass to it. For example, if you pass it a string (eg 'nav' ), it will find every nav element in the document and return a set of jQuery objects (elements) - one for each DOM element it finds. When you say var nav = $('nav'); , you are assigning this set of jQuery objects to your nav variable, so you can work with it later. So far so good.

Instead of passing a string to $ , you technically could pass jQuery objects back into the $ function, which is what you are doing when you say $(nav).hide(); . DOING THIS MAKES LITTLE SENSE - it will just return the same array of jQuery objects, nav , which you put into it in the first place!!

Personally, I like to prefix any variable which holds a jQuery object with a $ sign, ie var $nav = $('nav'); . This is just a convention that allows me to see at a glance that this variable holds a jQuery object (element) rather than a native DOM element, or integer, or so on. If I ever see $($myVar) in my code, I know it's probably time for bed...

Update: there are other things that it DOES make sense to pass into the $() function, apart from strings. Passing in a DOM element, for example (such as saying $(document) ) creates a jQuery object representation of that DOM element, which can be very useful.

All of these answers are pieces to the entire answer . . . let me add yet another piece. :)

As others have said, the $(...) notation is a JQuery function that returns a JQuery object. Depending on what "..." is, determines how that is done.

Some examples:

  • if you put a selector, such as "div", in there, you will get a JQuery object that contains all of the DOM elements that match the selector pattern . . . in this case, all of the <div> elements.

  • if you pass a string representation of an HTML element (eg, "<div></div>" ), you will get a JQuery object that points to a newly created <div> element.

  • if you put a DOM node reference in there (eg, one created by using document.getElementsByTagName("div") ), it will create a JQuery object that points to that node(s) in the reference.

The whole point of this is that JQuery works with JQuery objects, so these various functions help programmers create them.

Now this is where we get to your question . . .

Each time you use $("...") , you are creating a brand new object, so, for example the following code will produce two unique JQuery objects, each of which pointing to the identical DOM elements:

var $firstObject = $("div");
var $secondObject = $("div");

So, if you do a comparison of them (like this ($firstObject === $secondObject) ), they will not be seen as equal, because they are not the same object.

Now, let me do a slight variation of your second example to add a little more clarity. If you create a third variable and set it equal to the second one, like this:

var $thirdObject = $secondObject;

. . . you have two elements that are actually pointing to the same JQuery object, so they ARE actually equal (ie, ($secondObject === $thirdObject) will evaluate as true).

Now finally, what you've shown with this peice of code:

$(nav).hide();

. . . is simply another example of trying to create a JQuery object . . . this time using another JQuery object. Doing this with that third variable that I created above, however, will now break the relationship that it has with the second variable . . . ($secondObject === $($thirdObject)) . . . they are no longer equal, because the two sides of the comparison no longer point to the same object. Much like the comparison between $firstObject and $secondObject from earlier, that comparison is using two unique JQuery objects.

However . . .

Unlike some of the other answers, I would disagree that it is a completely incorrect form of coding . . . while I would never use it in the situation that you provide in your example, passing a JQuery object into the $(...) function is essentially the same thing as using .clone() . The two $bar assignments below are functionally equivalent:

var $foo = $("<div></div>");

var $bar = $($foo);
var $bar = $foo.clone();

The JQuery API even makes the same point ( http://api.jquery.com/jQuery/ ):

Cloning jQuery Objects

When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.

EDIT :

Out of curiosity, I set up a quick test at jsPerf and the $($foo) approach is pretty significantly faster than .clone() in Firefox, IE9, and Chrome: http://jsperf.com/clone-technique-test

var nav = $('nav');

$(nav).hide();

nav is already a jQuery object so $(nav) is useless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM