简体   繁体   中英

Javascript & JQuery: what's the difference between $x and x as variable declarations?

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

x and $x are simply two different variables. When it comes 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, eg, 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM