What's the difference between ‘var $x’ and ‘var x’ in javascript? [duplicate]
What's the difference between var $x
and var x
in javascript?
Nothing. People tend to use the $x syntax because it's easier to remember you're dealing with a jquery object rather than an element or an id.
In general I tend to use something similar to:
var $x = $(selector) //$x holds reference to a jquery object
var elX = document.getElementById(id); // elX hold ref to an element node
var xId = $(selector).attr('id'); //xId holds ref to an id attribute
The difference? One variable starts with $
.
And neither has anything to do with jQuery - it's just javascript.
One declares a variable called $x
, one declares a variable called x
. Dollar is a perfectly valid character for a variable name in JavaScript (this isn't really specifically jQuery related as far as I can see).
See "Why would a javascript variable start with a dollar sign?" for more.
There is no difference between two in JavaScript. $ is allowed in variable declaration in JavaScript
The dollar prefix is often used in Javascript for global variables. It's merely a convention - Like underscore is often used to denote a private member.
精彩评论