88

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?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
dnagirl
  • 20,196
  • 13
  • 80
  • 123

5 Answers5

234

$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.

Kyle
  • 65,599
  • 28
  • 144
  • 152
David Hellsing
  • 106,495
  • 44
  • 176
  • 212
30

This is pure JavaScript.

There is nothing special about $. It is just a character that may be used in variable names.

var $ = 1;
var $$ = 2;
alert($ + $$);

jQuery just assigns it's core function to a variable called $. The code you have assigns this to a local variable called self and the results of calling jQuery with this as an argument to a global variable called $self.

It's ugly, dirty, confusing, but $, self and $self are all different variables that happen to have similar names.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    Tastes vary, but I don't find it ugly at all. The dollar sign has been used to denote $STRINGS and other special variables for a long time. Definitely going to adopt this convention. – I. J. Kennedy Nov 02 '13 at 00:45
9

No, it certainly is not. It is just another variable name. The $() you're talking about is actually the jQuery core function. The $self is just a variable. You can even rename it to foo if you want, this doesn't change things. The $ (and _) are legal characters in a Javascript identifier.

Why this is done so is often just some code convention or to avoid clashes with reversed keywords. I often use it for $this as follows:

var $this = $(this);
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
7

self and $self aren't the same. The former is the object pointed to by "this" and the latter a jQuery object whose "scope" is the object pointed to by "this". Similarly, $body isn't the body DOM element but the jQuery object whose scope is the body element.

Rich
  • 3,095
  • 17
  • 17
2

The dollarsign as a prefix in the var name is a usage from the concept of the hungarian notation.

Jan
  • 101
  • 2
  • 6