Learn the global variables of JavaScript with me _javascript tips

Source: Internet
Author: User

One, try to use the global object as little as possible

The problem with global variables is that both your JavaScript application and all the code on the Web page share these global variables, and they live in the same global namespace, so naming conflicts are unavoidable when the two different parts of the program define a global variable with the same name but different roles.

It is also common for Web pages to contain code that is not written by the developer of the page, for example:

    • Third-party JavaScript libraries
    • Script code for advertising Party
    • Third-party user tracking and profiling script code
    • Different types of small components, flags and buttons

For example, the third party script defines a global variable called result, and then defines a global variable named result in your function. The result is that the following variables cover the front, and the third party script will suddenly be a fart!

Because, if you're not careful, modifying a global variable at one point in the code can cause other modules that depend on the global variable to make an error. And the cause of the error is difficult to debug, difficult to find.

In addition, the Web page must run with the Window object, and the browser engine goes through the properties of the window again, and the performance drops.

    • Global variable is the link between different modules, the module can only access through global variables to provide the function
    • When you can use a local variable, never use a global variable
var i,n,sum//globals
function Averagescore (players) {
 sum =0;
 for (i = 1, i = player.length i<n; i++) {
  sum = score (players[i]);
 return sum/n;
}

Keep these variables as local variables, just as part of the code that needs to use them.

function Averagescore (players) {
var i,n,sum;
 Sum =0;
 for (i = 1, i = player.length i<n; i++) {
  sum = score (players[i]);
 return sum/n;
}

In browser, the This keyword points to the Global window object
The global namespace of JavaScript is also exposed as a global object that can be accessed in the program global scope, which is the initial value of the This keyword. In a Web browser, global objects are bound to global window variables. Adding or modifying a global variable automatically updates the Global object.

This.foo; Undefined
foo = "global foo";//"Global foo"
This.foo;//"Global foo"

Similarly, updating global objects automatically updates the global namespace:

var foo = "Global foo";
This.foo; "Global foo"
This.foo = "changed";
Foo "Changed"

Two ways to change the global object by declaring the Var keyword and setting the property to the global object (through the This keyword)

Feature detection (Feature detection) for the current running environment through global objects, such as providing a JSON object for manipulating JSON data in ES5, you can pass the if (this. JSON) to determine if the current running environment supports JSON

if (!this. JSON) {This
 . JSON ={
  Parse: ...,
  stringify: ...
 }
}

Ii. How to avoid global variables

Method One: 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 two: Using module mode

var serial_maker = function () {

//produce an object that produces unique strings. A
//Unique string is made up 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"

   

A modular pattern is the creation of a function that includes a private variable and a privileged object, the content of which is a function that can access a private variable using a closure, and finally returns a privileged object.

First, method two 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, it will immediately error, because this is an object, not a string.

Method 3:0 Global Variables

0 Global variables are actually a kind of local variable processing method to adapt to a small block of code, only suitable for use in some special scenes. The most common is a few completely independent scripts that are not accessed by other scripts.
The use of 0 global variables requires an immediate execution function, as follows.

(function (Win) {

 ' use strict ';
 var doc = win.document;
 Define other variables here and write code
})

Third, unexpected global variables

Because of the two features of JavaScript, it is surprisingly easy to create global variables unconsciously. First, you can use variables without even having to declare them; second, JavaScript has an implied global concept, meaning that any variable you don't declare will become a global object attribute. Refer to the following code:

function sum (x, y) {
 //deprecated notation: Implicit global variable result
 = x + y;
 return result;
}

Result in this code is not declared. The code works just fine, but after calling the function, you end up with one more global namespace, which can be a source of problems.

The rule of thumb is to always declare a variable with VAR, as demonstrated by the improved sum () function:

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

Another example of creating an implicit global variable is to use a task chain to make a partial var declaration. In the following fragment, A is a local variable but B does have a global variable, which may not be what you want to happen:

In inverse case, do not use
function foo () {
 var a = b = 0;
 // ...
}

This behavior occurs because of this right-to-left assignment, first of all, the assignment expression B = 0, in which 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 by var. In other words, it's like you enter:

var a = (b = 0);
If you are ready to declare variables, it is a good practice to use a chain assignment that does not produce any unexpected global variables, such as:

function foo () {
 var a, b;
 .. A = b = 0; Two all local variables
}

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

Always remember to declare local variables with the VAR keyword

Use the lint tool to ensure that no implicitly-declared global variables

The above is the global variable description of JavaScript, I hope to help you learn.

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.