search
HomeWeb Front-endJS TutorialLearn javascript global variables with me_javascript skills

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

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

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"

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

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

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:...
 }
}

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 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 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 ;
 //在此定义其他的变量并书写代码
} )

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

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

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

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

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

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

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

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

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

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

Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version