Learn from me about javascript's global variables

  • 2020-11-03 22:00:21
  • OfStack

1. Minimize the use of global objects

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

It is also common for web pages to contain code that is not written by the developer of the page, such as:

The JavaScript library for the third party Advertising side of the script code The third party user tracks and analyzes the script code Different types of widgets, logos and buttons

For example, the third party script defines a global variable called result. Next, define a global variable called result in your function. The result is that after the variable overrides the front, the third side of the script on 1 hiccup bullshit!

Because you accidentally modify a global variable in one part of your code, it can cause errors in other modules that depend on it. And the cause of the error is difficult to debug, difficult to find.

On the other hand, web pages must run with window objects, and the browser engine has to iterate over window's properties once again, which degrades performance.

Global variables are the bonds that hold different modules together. Modules can only access functions provided by each other through global variables Never use global variables when you can use local variables

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 local and treat them as just one 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 is accessible within the program global scope, which serves as the initial value of the this keyword. In the Web browser, the global object is bound to the global window variable. 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 a global object automatically updates the global namespace:


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

Two ways to change a global object are through the var keyword declaration and by setting properties on the global object (via the this keyword)

For example, if an JSON object is provided in ES5 to manipulate JSON data, then if(this.JSON) can be used to determine whether the current running environment supports JSON or not


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"
 }
};

Approach 2: Use modular 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 module pattern is to create a function that contains a private variable and a privileged object, and the content of the privileged object is the function that has access to the private variable using the closure, and finally returns the privileged object.

First, method 2 can be used not only as a global variable, but also to declare global variables locally. Because even if you change seqer somewhere and you don't know it, you'll immediately report an error because it's an object, not a string.

Method 3: Zero global variables

The zero global variable is actually a local variable handling method adopted to accommodate 1 small piece of closed code and is only suitable for use in 1 special scenario. The most common ones are completely independent scripts that are not accessed by other scripts.
Using zero global variables requires immediate execution of functions, as follows.


( function ( win ) {

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

Unexpected global variables

Because of two characteristics of JavaScript, it is surprisingly easy to create global variables automatically. First, you can use variables without even declaring them; Second, JavaScript has an implicit global concept, meaning that any variable you do not declare becomes a global object property. Refer to the following code:


function sum(x, y) {
 //  It's not recommended :  Implicit global variables 
 result = x + y;
 return result;
}

result in this code is not declared. The code works fine, but you end up with an extra global namespace after calling the function, which can be the source of a problem.

The rule of thumb is to always declare variables using var, as demonstrated by the improved sum() function:


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

Another counter example of creating an implicit global variable is using the task chain to make part of the var declaration. In the following snippet, a is a local variable but b is a global variable, which may not be what you want to happen:


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;
}

0

This happens because of the assignment from right to left. First, the assignment expression b = 0, in which case b is undeclared. The expression returns a value of 0, which is then assigned to the local variable, a, defined by var. In other words, it's as if you typed:

var a = (b = 0);
If you are ready to declare variables, it is a good practice to use chain allocation instead of producing any unexpected global variables, such as:


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;
}

1

However, another reason to avoid global variables is portability. If you want your code to run in a different environment (on a host), using global variables is treading on thin ice, because you'll inadvertently overwrite host objects that don't exist in your original environment

Always remember to declare local variables with the var keyword

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

Above is the introduction of javascript global variables, I hope to help you learn.


Related articles: