Global variables are the devil.
Because, you are not careful, modifying the global variable in a certain part of the code will lead to errors in other modules dependent on the global variable. The cause of the error is difficult to debug and difficult to find.
Furthermore, the window object must be used for webpage running, and the browser engine must traverse the properties of the window again, reducing the performance.
So how to avoid
Method 1: create only one global variable.
MyApp. stooge = {
"First-name": "Joe ",
"Last-name": "Howard"
};
MyApp. Flight = {
Airline: "oceanic ",
Number: 815,
Departure :{
IATA: "Syd ",
Time ",
City: "sysydney"
},
Arrival :{
IATA: "LAX ",
Time ",
City: "Los Angeles"
}
};
Method 2: Use the module Mode
VaR serial_maker = function (){
// Produce an object that produces unique strings.
// Unique string is made up of two parts: a prefix
// And a sequence number. The object comes
// Methods for setting the prefix and Sequence
// Number, and a gensym method that produces unique
// Strings.
VaR prefix = '';
VaR seq = 0;
Return {
Set_prefix: function (p ){
Prefix = string (P );
},
Set_seq: function (s ){
SEQ = s;
},
Gensym: function (){
VaR result = prefix + seq;
SEQ + = 1;
Return result;
}
};
}();
VaR seqer = serial_maker ();
Seqer. set_prefix = 'q ';
Seqer. set_sequence = 1000;
VaR unique = seqer. gensym (); // unique is "q1000"
The so-called module mode is to create a function, which includes private variables and a privileged object. The content of a privileged object is a function that can access private variables using closures, finally, the privileged object is returned.
First, method 2 can be used not only as a global variable, but also as a local declaration of a global variable. Because even if you do not know where to modify the seqer, an error is reported immediately because it is an object, not a string.