Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the meaning of $ in front of a variable

Tags:

jquery

The $ dollar sign in front of (this) serves to select the current element. I'm a little confused about the $ in front of option and thisSelect. Do they have a special meaning?

var $options = $(this).children('option');
var $thisSelect = $(this);

Thanks for helping

like image 549
Richard77 Avatar asked Jan 16 '13 16:01

Richard77


1 Answers

As everyone said, its just a convention.
I use the $ sign in front of a variable to identify that this variable holds an object.

var thisIsANumber = 1024; // No $.. Its a normal variable
var $divElement = $('div#idOfDiv'); // Yes! Its a jQuery Object
var $this = $(this); // Commonly used to reduce the work javascript has to do!

//Now I can use something like this.. (Notice how easy it is to read!)
$divElement.slideUp();

// Or a more `real world` example!
$('#element').click(function(){
    // Hold $(this) inside a variable
    // So we don't have to traverse the dom unnecessarily
    var $this = $(this); // Save it (its a object.. so prepend a `$` )
    $this.hide(); // Use it again
    $this.fadeIn(); // and again
//  ^ Has a dollar sign, because it is a jQuery Object.
});

You will see loads of plugins use this convention (well.. at least the well written ones).
By storing the object inside a variable, Javascript doesn't have to crawl through your code each time to get the element. Instead, we already have the element (inside the variable), so we use that to reference it.

If you use $(this) more then once inside the same callback function, you should store it inside a variable.. (var $this = $(this);). Otherwise, every time you use it, javascript will have to get the element from your source code each time (which can massively decrease performance! (especially for people browsing on a slow/old computer!).

like image 169
Anil Avatar answered Sep 29 '22 08:09

Anil