javascript - How to use Global Variables in jQuery -


how can take global variables in jquery. syntax right i'm using.

var $val = 2;       or val = 2; (without using var keyword). 

thnx.

first , foremost: avoid using global variables whenever possible. (almost) possible. (with apologies dalai lama)

but answering question:

if use var @ global scope (outside of functions), creates global variable.

if assign variable haven't declared anywhere, if you're not using strict mode (and recommend use it), create global implicitly. the horror of implicit globals , should avoided.

if really, need create global variable without using var @ global scope, can without horror explicitly using window object:

window.val = 2; 

but reiterate opening point: avoid globals.

here's 1 way that: use scoping function around of code:

(function() { // <== start of scoping function     // code here, `var`s here global *your* code not globals     // ... })();         // <== end of scoping function, , () call 

you should avoid globals within code, using scoping function, @ least protect outside world (and vice-versa).


Comments