Home > Web Front-end > JS Tutorial > body text

Learn javascript global variables with me_javascript skills

WBOY
Release: 2016-05-16 15:32:11
Original
1244 people have browsed it

1. Use global objects as little as possible

The problem with global variables is that these global variables are shared by all the code in your JavaScript application and the web page. They live in the same global namespace, so when two different parts of the program define the same name but have different functions When using global variables, naming conflicts are inevitable.

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

  • Third-party JavaScript library
  • Advertiser’s script code
  • Third-party user tracking and analysis script code
  • Different types of widgets, flags and buttons

For example, the third-party script defines a global variable called result; then, also defines a global variable named result in your function. The result is that the later variables overwrite the previous ones, and the third-party script suddenly burps!

Because if you accidentally modify the global variable somewhere in the code, it will cause errors in other modules that rely on the global variable. Moreover, the cause of the error is difficult to debug and find.

Furthermore, the window object must be used to run the web page, and the browser engine has to traverse the properties of the window again, resulting in reduced performance.

  • Global variables are the link between different modules. Modules can only access the 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;
}

Copy after login

Keep these variables local and only use them 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;
}

Copy after login

In the browser, the this keyword will point to the global window object
JavaScript's global namespace is also exposed as a global object accessible in the program's global scope, which serves as the initial value of the this keyword. In web browsers, global objects are 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"

Copy after login

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

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

Copy after login

Two ways to change the global object, declaring it through the var keyword and setting attributes on the global object (through the this keyword)

Use global objects to perform feature detection (Feature Detection) for the current running environment. For example, ES5 provides a JSON object to operate JSON data, then you can use if (this.JSON) to determine whether the current running environment supports it. JSON

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

Copy after login

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

Copy after login

Method 2: Use 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"
Copy after login

The so-called module mode is to create a function, which includes private variables and a privileged object. The content of the privileged object is that the private variables can be accessed using closures. function, and finally returns the privileged object.

First of all, method two can not only be used as a global variable, but can also be used to declare global variables locally. Because even if you modify seqer somewhere unknown, an error will be reported immediately because it is an object, not a string.

Method 3: Zero global variables

Zero global variables are actually a local variable processing method adopted to adapt to a small section of closed code, and are only suitable for use in some special scenarios. The most common ones are completely independent scripts that are not accessed by other scripts.
To use zero global variables, you need to use an immediate execution function. The usage is as follows.

( function ( win ) {

 'use strict' ;
 var doc = win.document ;
 //在此定义其他的变量并书写代码
} )

Copy after login

3. Unexpected global variables

Due to two characteristics of JavaScript, it is surprisingly easy to create global variables unconsciously. First, you can use variables without even declaring them; second, JavaScript has the concept of implicit globals, which means that any variable you don't declare becomes a global object property. Refer to the code below:

function sum(x, y) {
 // 不推荐写法: 隐式全局变量
 result = x + y;
 return result;
}

Copy after login

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

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

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

Copy after login

Another counter-example to creating implicit global variables is using task chains for partial var declarations. In the following snippet, a is a local variable but b is a global variable, which is probably not what you want:

// 反例,勿使用
function foo() {
 var a = b = 0;
 // ...
}

Copy after login

此现象发生的原因在于这个从右到左的赋值,首先,是赋值表达式b = 0,此情况下b是未声明的。这个表达式的返回值是0,然后这个0就分配给了通过var定义的这个局部变量a。换句话说,就好比你输入了:

var a = (b = 0);
如果你已经准备好声明变量,使用链分配是比较好的做法,不会产生任何意料之外的全局变量,如:

function foo() {
 var a, b;
 // ... a = b = 0; // 两个均局部变量
}

Copy after login

然而,另外一个避免全局变量的原因是可移植性。如果你想你的代码在不同的环境下(主机下)运行,使用全局变量如履薄冰,因为你会无意中覆盖你最初环境下不存在的主机对象

  总是记得通过var关键字来声明局部变量

 使用lint工具来确保没有隐式声明的全局变量

以上就是对javascript的全局变量介绍,希望对大家的学习有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!