2

I'm new to jQuery and have noticed someone go:

var $this = $(this);

Why do this? Is it to save typing? Does it help performance? Is it fairly standard practice?

Also I've started doing things such as:

var minus_button = $('#minus_button');

Should this instead be var $minus_button = $('#minus_button'); to signal it's a jquery object?

I read http://docs.jquery.com/JQuery_Core_Style_Guidelines but couldn't find any suggestions.

Rusty Rob
  • 16,489
  • 8
  • 100
  • 116
  • Also from here http://stackoverflow.com/questions/1916584/jquery-variable-syntax I noticed someone uses $self ? – Rusty Rob Jun 15 '12 at 01:59

2 Answers2

6

Yes, it's a naming convention to signal that that variable is a jquery object reference. That way it is very obvious whether or not you can use a jquery function on the object or if the object needs to be converted into a jquery object to apply said function.

Example:

var element = document.getElementById('myelement');
var $element = $('#myelement');

// not a jquery object
console.log($(element).val());
// jquery object
console.log($element.val());
Gabe
  • 49,577
  • 28
  • 142
  • 181
  • weird, i would have thought $(document.getElementById('z')) would be exactly the same as $('#z') – Rusty Rob Jun 15 '12 at 02:11
  • Well it is, they both return a jquery object. My example is a little different than that. – Gabe Jun 15 '12 at 02:14
  • don't you essentially compare $(element) to $element in your example? – Rusty Rob Jun 15 '12 at 02:25
  • 1
    I am showing you that in order to use a jquery function you need to have a reference to jquery object first. So I do getElementId which returns me a DOM element. With the naming convention in question, i don't prefix the variable name with a $. So when I want to apply a jquery function later, I have to convert it into a jquery object. I was merely showing how the $ makes it more readable and when I went to apply a jquery function, I knew the `element` object was not a jquery object by the name of the object alone. – Gabe Jun 15 '12 at 02:29
  • 1
    Also it caches the element so you don't have to repeatedly go through the dom to find it. So if you have to repeatedly get an element it improve's performance – wirey00 Jun 15 '12 at 02:37
1

It's just a form of Hungarian Notation.