JavaScript methods and benefits of reducing global variables

Source: Internet
Author: User

I used to encapsulate a very large ship monitoring JS plugin based on Google Maps. At that time due to lack of entry, coupled with the lack of experience, resulting in JS writing is not good, global variables are everywhere. To the back, the previous global variable will be overwritten. Today, consider the problems caused by using too many global variables.

First, how the global variables are generated

We know that global variables are mounted on the Window object. There are many ways of producing it, listed below.

1, human-defined

The human definition is simple, and the code you write defines a global variable person:

123 <scripttype="text/javascript">    var person = ‘刘备‘;</script>

2, missing write Var

Many people think that the variables written inside the function are only valid within the function. In fact JavaScript is not like that. If you do not write Var when you define a variable within a function, it is still a global variable.

1234567 < script  type = "Text/javascript" > &NBSP;&NBSP;&NBSP;&NBSP; function sayname ()  {           name =  ' Liu Bei '; &NBSP;&NBSP;&NBSP;&NBSP; } &NBSP;&NBSP;&NBSP;&NBSP; sayname (); &NBSP;&NBSP;&NBSP;&NBSP; alert (name);     //Eject Liu Bei </ script >

Notice that once name is called, a global variable of name is created and accessible everywhere.

Only in strict mode does the browser prompt for an error: name is undefined;

There is a fire code that uses JSLint or jshint scan codes to clarify these unintended global variables.

Second, too many global variables will cause problems

Of course, a small number of global variables do not cause much impact. But if the JS code is huge, what's the problem with global variables everywhere?

1. Naming conflicts

Global variables too much, we may unintentionally declare a global variable, actually existed before. This is likely to result in subsequent values overwriting the preceding values.

2. Weak code

For example, in a function to rely on a global variable, once the global variable is deleted or modified, it will affect the execution of this function is correct.

12345678 varname = ‘刘备‘;function sayName() {    alert(name)}//改为参数传入好于依赖全局对象functionsayName2(name) {    alert(name);}

For example, for the above two functions, the dependency parameter deposit is better than the dependent global variable.

3. Difficult to test

After you rely on global variables, the entire framework relies on global variables to run. Therefore, in order to perform local or unit tests, it is necessary to create a complete global environment.

Third, the method of reducing global variables

There are many ways to reduce global variables, and here are a few recommendations.

1. Single Global variables

The single global variable means that only one global variable is created. The other global variables are then attached to the global variable as attributes.

Like what:

    • jquery defines two global objects: $ and jquery.

    • Yui defines a unique global object for the Yui global object.

    • Dojo defines a global object for dojo.

For example, I want to implement the following logic:

12345678910 functionPerson(id, name){    this.id = id;    this.name = name;}Person.prototype.sayAge = function(age) {    alert(age);}varp1 = newPerson(1, ‘刘备‘);varp2 = new Person(2, ‘关羽‘);

The above code logic creates 1 global functions, 2 Global objects: Person, p1, p2.

In fact, you can simply create an object to do the same thing.

1234567891011 varmyjs = {};myjs.Person = function(id, name){    this.id = id;    this.name = name;}myjs.Person.prototype.sayAge = function(age) {    alert(age);}myjs.p1 = newmyjs.Person(1, ‘刘备‘);myjs.p2 = newmyjs.Person(2, ‘关羽‘);

The above code, all the global functions and global objects are attached to the global object Myjs.

In fact, you can also mount more variables, objects, functions, and so on.

2. Namespaces

Based on a single global variable, when the variable is too long, only one level can cause an issue with the same name overlay. At this point, we will create a multi-level variable mount in the way of the namespace.

The concept of namespaces does not exist in JavaScript, but is actually a functional division that skillfully leverages JavaScript's code features.

Yahoo Yui is to follow the idea of the namespace to manage its code.

For example, all methods under Y.dom are related to DOM operations, and all methods under Y.event are related to events.

In JavaScript, we can easily use objects to create our own namespaces.

For example, suppose a ship monitoring system is encapsulated based on a map:

123 varmyjs = {};myjs.map = {};  //地图操作相关的myjs.ship = {}; //船舶操作相关的

In the way of this namespace, it is important to be aware that the namespace exists before use.

For example:

123 MyGlobal.Person.Say.SayHello = function() {    alert(‘hello‘);}

Using the MyGlobal.Person.Say namespace, you will get an error when the person object does not exist under Myglobal. This can write a function for Myglobal, which is created when there is no namespace, and returns directly if the namespace already exists. This allows you to omit the problem that you want to use to determine the namespace:

12345678910111213141516171819202122 varMyGlobal = {    namespace: function(ns) {        varparts = ns.split(‘.‘);        varobject = this;        vari;        varlen;        for(i = 0, len = parts.length; i < len; i++)        {            if(!object[parts[i]])            {                object[parts[i]] = {};            }            object = object[[parts[i]]]        }        returnobject;    }}//不用判断命名空间是否存在的情况下直接使用;MyGlobal.namespace("Person.Say");  //namespace函数当明明空间存在时会返回,不存在时会创建再返回,MyGlobal.Person.Say.SayHello = function() {    alert(‘hello‘);}

Before you want to use any namespace, just call it: Myglobal.namespace ("Person.say");

3, Modular

This thing has to be long-winded, to be written in an independent article.

4, 0 global variables (closures)

The use of the closure of the scene is not many, when I need a JS, and this JS does not need to be other JS access, just to achieve a single function and created. You can check out this article, "JavaScript closures," to easily learn how to close a packet.

The simplest closure:

1234 (function(win){    //...自己的代码逻辑,有权访问外部。}(window));

You can write your own logic in "Your own code logic". This approach has the following two requirements:

    • The code does not need to be relied upon by other code;

    • Code does not need to be extended frequently;

That is, the script is very short and does not need to interact with other JS in order to use this kind of closure method. In fact, it really does not use a lot of scenes.

Source: JavaScript methods and benefits of reducing global variables

JavaScript methods and benefits of reducing global variables

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.