Avoidance of global JavaScript variables (notes on the essence of JavaScript LANGUAGE)

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.