Reputation: 79
Can anyone tell me what is the difference between variables $variable and $.Variable in jQuery? For examle:
$x='3';
$.y(parseInt($(this).val())
Upvotes: 3
Views: 487
Reputation: 25679
In JavaScript, you can have variable names contain the character $
. If you create a new HTML document with a script tag, you can just do:
var $test = 10;
console.log($test);
And it will log 10
to the console.
jQuery uses the $
variable as a shorthand to itself, and any jQuery functions/extensions are available off of that object. The following might make it more clear:
// Assume you have already loaded jQuery
$ == jQuery; // true!
$.test = 10; // Assign a random property to the "jQuery Object"
console.log($.test); // print out "10"
Now, in the case of your example, $.y()
, somebody has extended jQuery by adding a method named y
, which can be accessed as $.y()
. In many cases, as a way of keeping track of object types, if you have a variable that is a reference to a jQuery object, you prepend the variable name with dollarSign:
var header = document.getElementById("header"); //without jQuery
var $header = $("#header"); // with jQuery
The above is not a rule, and is just a convention that many people follow to keep their code clear.
Upvotes: 1
Reputation: 22820
$var
is just a convention to tell that the var holds a jQuery wrapped DOM selection, e.g.:
var $form = $('#yourForm');
$.function
on the other hand means that you are calling some "static" function of jQuery library, e.g. $.each()
, without performing any DOM selection.
Upvotes: 3
Reputation: 9929
The first one ($x) is a variable (that in this case is assigned a value of the string 3. The second one is a function call to the function y(), which is assumably a jquery extension function. In your example this function gets an argument that contains the some integer coming from the value of something that is referenced by $(this).
Note that $x could just as easily have been var x = '3'. The assignment in your example is actually a bit weird because the $ prefix usually indicates that the variable is holding some jQuery selector result.
Upvotes: 5