Jquery variable syntax

I am learning jQuery trying to understand other people's code. I came across 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 } 

I understand that $ refers to a jQuery object. So why put $ with $self and $body ? And does self match $self ?

+75
jquery syntax
Dec 16 '09 at 18:15
source share
5 answers

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

Example:

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

They are declared as two different variables. This is like an underscore in front of private variables.

Somewhat popular template:

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

So you know that $ foo is a cached jQuery object later in the code.

+190
Dec 16 '09 at 18:23
source share

This is pure JavaScript.

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

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

jQuery simply assigns its main function a variable called $ . The code that you assign this local variable called self and the results of calling jQuery with this as an argument to a global variable named $self .

This is ugly, dirty, confusing, but $ , self and $self are all different variables that have similar names.

+26
Dec 16 '09 at 18:30
source share

No, of course not. This is just another variable name. $() you are talking about is actually the main jQuery function . $self is just a variable. You can even rename it to foo if you want, this will not change the situation. $ (and _ ) are legal characters in a Javascript identifier.

Why this is done so often happens only in some code or to avoid collisions with canceled keywords. I often use it for $this as follows:

 var $this = $(this); 
+9
Dec 16 '09 at 18:19
source share

self and $ self do not match. The first object that this points to and the last jQuery object whose scope is the object that this points to. Similarly, $ body is not a DOM element of the body, but a jQuery object, the volume of which is the body element.

+7
Dec 16 '09 at 18:19
source share

The price mark as a prefix in the name var is the use of the concept of Hungarian notation .

+2
Jun 14 '12 at 23:17
source share



All Articles