admin管理员组

文章数量:1302870

In Javascript & JQuery, what's the difference between $x and x as variable declarations? For example, if I declare

var x = 5;
$x = 5;
x = 5;

am I just saying the same thing or is there a scope implication or am I just getting confused because I've been coding in several different languages?

Thanks, Debbie

In Javascript & JQuery, what's the difference between $x and x as variable declarations? For example, if I declare

var x = 5;
$x = 5;
x = 5;

am I just saying the same thing or is there a scope implication or am I just getting confused because I've been coding in several different languages?

Thanks, Debbie

Share asked Jun 4, 2012 at 1:50 Deborah ColeDeborah Cole 3,0563 gold badges22 silver badges19 bronze badges 2
  • This is really two separate JavaScript/jQuery questions. 1) How are x and $x different as variables and 2) How does using var affect a variable's scope. – j08691 Commented Jun 4, 2012 at 1:58
  • "In Javascript & JQuery" - note that jQuery is 100% JavaScript, both the library itself and all code that uses the library, so jQuery doesn't provide different syntax (for variables or anything else). – nnnnnn Commented Jun 4, 2012 at 2:02
Add a ment  | 

2 Answers 2

Reset to default 12

x and $x are simply two different variables. When it es to naming JavaScript variables the dollar sign is just another character that has no special meaning.

Some people (including me) tend to name JS variables with a dollar-sign prefix if that variable is expected to hold a jQuery object, e.g., var $x = $("div"), but that is just a convention to make it easier to remember what the variable is for, it makes no difference at all as far as the JS interpreter is concerned.

In the code in the question, $x will be a global variable not because of the $ but because any variable not declared with the var statement is automatically global.

x and $x are two different variables. The first line declares a variable x and assigns it a value. The second line assigns a value to variable $x which, all else being equal, will be implicitly declared with global scope as long as you are not running in strict mode. The third line re-assigns to previously declared variable x.

本文标签: Javascript amp JQuery what39s the difference between x and x as variable declarationsStack Overflow