Question

So I recently discovered that it is useful to name jQuery variables in a way that starts with "$" sign, so var $progress instead of var progress for example.

What I don't understand is, how do you know when to use this? I mean there is such a thin line between javascript and jQuery (there isn't even a line, jQuery is JavaScript) would I use it on variables that are changed with jQuery or something?

At this moment it seems to me that if you have a jQuery based solution that all variables would end up starting with "$", so I'd like to know when to actually do this so I don't confuse myself and others.

Était-ce utile?

La solution

There is no need to use $ at the beginning of variable names and some developers actually hate the practice altogether, though I do personally like it. The common use is to note that the value of that variable is a jQuery object.

A jQuery object is what is created in this process:

var $myElement = $('#some-id');

That notes that $myElement contains a jQuery object and therefore it is safe to use jQuery functions on it. For example, $myElement.hide();

Without jQuery, this is how the same code might look:

var myElement = document.getElementById('some-id');
myElement.style.display = 'none';

In that case, myElement is NOT a jQuery object and so myElement.hide() is an error. This is an example of why someone may prefer to have the $ on the variable name... to note that jQuery functions can be called on it. If someone is using jQuery already, it is standard to get all element references with jQuery anyway, so this actually is redundant.

Autres conseils

This is really all about coding standards that you and your team have to decide on. It's the same as debating underscores or pascal casing or any other naming convention that you can come up with.

In short: It comes down to personal preference.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top