jquery variable syntax

dnagirl picture dnagirl · Dec 16, 2009 · Viewed 362.4k times · Source

I'm learning jQuery by trying to understand other people's code. I ran into this:

jQuery.fn.myFunc = function(options, callback) {

//stuff

  jQuery(this)[settings.event](function(e) {
    var self = this,
    $self = jQuery( this ),
    $body = jQuery( "body" );
     //etc.
  }

//more stuff

}

My understanding is that $ refers to the jQuery object. So why put $ with $self and $body? And is self the same as $self?

Answer

David Hellsing picture David Hellsing · Dec 16, 2009

$self has little to do with $, which is an alias for jQuery in this case. Some people prefer to put a dollar sign together with the variable to make a distinction between regular vars and jQuery objects.

example:

var self = 'some string';
var $self = 'another string';

These are declared as two different variables. It's like putting underscore before private variables.

A somewhat popular pattern is:

var foo = 'some string';
var $foo = $('.foo');

That way, you know $foo is a cached jQuery object later on in the code.