JavaScript -- Item5 global variable that you don't know

Source: Internet
Author: User

JavaScript -- Item5 global variable that you don't know
1. Use as few global objects as possible

The problem with global variables is that your JavaScript Application and all the code on the Web page share these global variables. They live in the same global namespace, therefore, when two different parts of the program define global variables with the same name but different roles, naming conflicts are inevitable.

The web page contains code that is not written by the page developer. For example:

Third-party JavaScript library advertiser script code third-party users track and analyze script code different types of widgets, logos and buttons

For example, the third-party script defines a global variable called result. Then, you define a global variable named result in your function. The result is that the subsequent variables overwrite the previous ones, and a third-party script will immediately fart!

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.

Global variables are the bond between different modules. global variables can only be used between modules to access functions provided by each other.

Do not use global variables when using local variables.

var i,n,sum//globalsfunction averageScore(players){    sum =0;    for(i = 1, i = player.length; i
  

Keep these variables as local variables as part of the code that requires them.

function averageScore(players){var i,n,sum; sum =0; for(i = 1, i = player.length; i 
In browser, this keyword will point to the global window object

The global namespace of JavaScript is also exposed as a global object that can be accessed in the global scope of the program. this object serves as the initial value of the this keyword. In the Web browser, the global object is bound to the global window variable. When you add or modify a global variable, the global object is automatically updated.

this.foo; //undefinedfoo =global foo; //global foothis.foo; //global foo

Similarly, updating a global object will automatically update the global namespace:

var foo =global foo;this.foo; //global foothis.foo =changed;foo; //changed

Two methods are used to change the global object. The var keyword is used to declare and set attributes for the Global Object (through the this keyword)

The Feature Detection of the current running environment is detected through the Global Object. For example, if (this. JSON) to determine whether the current running environment supports JSON

if(!this.JSON){ this.JSON ={ parse:..., stringify:... }}
2. How to avoid global variables

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: 2004-09-22 14:55, city: Sydney }, arrival: { IATA: LAX, time: 2004-09-23 10:42, city: Los Angeles }};

Method 2: Use the module Mode

var serial_maker = function ( ) {// Produce an object that produces unique strings. A// unique string is made up of two parts: a prefix// and a sequence number. The object comes with// 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_seq = 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.

Method 3: zero global variables

Zero global variables are a local variable processing method to adapt to a small block of closed code. They are only suitable for some special scenarios. The most common is some completely independent scripts that won't be accessed by other scripts.
To use zero global variables, you must execute the function immediately. The usage is as follows.

(Function (win) {'use strict '; var doc = win.doc ument; // define other variables and write code here })
3. unexpected global variables

Due to the two features of JavaScript, it is unexpected to create a global variable unconsciously. First, you can use variables without even declaring them. Second, JavaScript has an implicit global concept, meaning that any variables you do not declare will become a global object attribute. Refer to the following code:

Function sum (x, y) {// not recommended Syntax: Implicit global variable result = x + y; return result ;}

The result in this code is not declared. The code works normally, but after calling a function, you have an extra global namespace in the final result, which can be the root cause of the problem.

The empirical rule is to always use var to declare variables, as demonstrated by the sum () function of the short version:

function sum(x, y) { var result = x + y; return result;}

Another inverse example of creating an implicit global variable is to useTask chainPartial var declaration. In the following snippet, a is a local variable but B is indeed a global variable, which may not happen as you wish:

// Inverse example, do not use function foo () {var a = B = 0 ;//...}

This phenomenon occurs becauseFrom right to leftFirst, the value assignment expression B = 0. In this case, B is not declared. The return value of this expression is 0, and then this 0 is assigned to the local variable a defined through var. In other words, you enter:

Var a = (B = 0 );
If you are ready to declare variables, it is better to use chain allocation without generating any unexpected global variables, such:

Function foo () {var a, B; //... a = B = 0; // both local variables}

However, another reason to avoid global variables is portability. If you want your code to run in different environments (under the host), use global variables such as thin ice, because you will accidentally overwrite host objects that do not exist in your original environment.

Always remember to declare local variables with the var keyword

UseLint ToolTo ensure that no global variables are implicitly declared.

 

Related Article

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.