Using PHP-style $globals in JavaScript
JavaScript has an implied global variable. When you do not use var to define a = 1, and you define a=1 directly, this variable a becomes a global variable. Some think this is a mistake and should avoid global variables, because they tend to make mistakes in unexpected places, especially in the case of many project participants.
In PHP, the default is a local variable. If you need a global variable, you must put the variable that you want to declare as a global variable into the $globals array.
How do you use $globals in javascripts? Through for the global convention in your javascripts? At the top of the script file, declare:
$GLOBALS = {};
So every time you need a global variable, you can do this:
$GLOBALS [' myglob '] = 1; //very much like the PHP style
Or if you like, you can do this:
$globals. Myglob = 1;
The advantages of doing this:
* Global variables are easy to identify (even visible from airplanes)
* If the variable is not defined as $global, then it is a local variable. If the variable does not use VAR, it will produce an error
Disadvantages:
* The use of this method is not official, not mandatory, but a conventional approach.
Stoyan Stefanov ' s blog:php-style $GLOBALS in Javascript?
Javascript has implied globals. When you skip the Var in var a = 1; and go a = 1;, then a becomes a global variable. Some consider this a error in the language. Global variables should is avoided because they tend to overwrite each of the other in unexpected places, especially if the Proje CT grows in LOC and number of developers.
In PHP at the other hand, variables are. If you need a global variable, then your have to have to is explicit about it using the $GLOBALS superglobal array.
So how about this:adopt the $GLOBALS convention in your javascripts? At the top of the script and go:
$GLOBALS = {};
Then every time your need a global variable, do:
$GLOBALS [' myglob '] = 1; Very php-like
Or if you prefer:
$GLOBALS. Myglob = 1;
Benefits of the approach:
global variables easy to spot (even from a aeroplane)
if it ' s not $GLOBAL, it's meant to being local. If it ' s missing the Var, it ' s an error
Drawback:
Dances ' s a convention, so It can only help, but not enforce any coding practices