How to Implement the standalone mode in JavaScript _ javascript tips-js tutorial

Source: Internet
Author: User
This article describes how to share a single mode in JavaScript. A single mode is defined as an object used to divide namespaces and organize a batch of related methods and attributes, if it can be instantiated, it can only be instantiated once. If you need it, you can refer to the single mode. As a software development mode, it is widely used in many object-oriented languages, in javascript, the single mode is also widely used, but the javascript language has its unique object-oriented method, as a result, although it is consistent with some traditional object-oriented languages in the idea of the single mode, there are still differences in implementation.

First, let's take a look at the definition of the single mode in the traditional object-oriented language: the single mode is a class that can only be instantiated once and accessed through a well-known access point. This definition highlights the features of traditional object-oriented languages, namely class and instantiation. Therefore, for traditional object-oriented languages, the standalone mode is based on its class and the natural features of Instantiation. That is, a class is defined using the keyword class, which can be instantiated using the new keyword, however, it is necessary to ensure that the same instance is obtained after each new instantiation, or the constructor can only be called once through new.

Let's take a look at the definition of the monomer mode in javascript: A monomer is an object used to divide the namespace and organize a batch of related methods and attributes together. If it can be instantiated, it can only be instantiated once. Compared with the above definition, you will find that the single definition here defines its essence as an object rather than a class in the traditional object-oriented language. This also shows that the javascript language is based on objects. At the same time, it is pointed out that if it can be instantiated, it indicates that there are several ways to define a single object in javascript, there are one or more ways to create a single object that can be instantiated by using the new keyword, but this method is not a natural feature of javascript itself, because the object created by using the new keyword, in fact, they all use functions to simulate the definition of their Constructor (although ES6 began to support the class keyword, it is not yet widely supported by browsers ), so how can we use the natural features of javascript to implement the single mode?

var Singleton={  attribute1:true,  attribute2:10,  method1:function(){  },  method2:function(arg){  }}

A Singleton object is defined here, which contains several attributes and methods on the page. This object is created when js is loaded and Singleton is used for calling. method1 is called. Its instantiation is completed when the page is loaded into the js parsing execution process. We didn't use the new keyword to instantiate this object, this is also a big difference between the implementation of the Single Mode in javascript and the traditional object-oriented language. This method is easier to understand. However, this method has several drawbacks. One obvious drawback is that it does not provide namespaces. If other programmers define a Singleton variable on the page, so it is easy to rewrite and confuse this single object. To solve this problem, rewrite it as follows:

var mySpace={};mySpace.Singleton={  attribute1:true,  attribute2:10,  method1:function(){  },  method2:function(arg){  }}


Here we first define a mySpace namespace, And then mount Singleton, a single object, under this object, which greatly reduces conflicts with other programmers and the possibility of misoperations, even if others define a Singleton variable in the global scope, this single object will not be contaminated, this achieves the namespace Division mentioned in the previous definition and organizes some related attributes and methods.

This method still has shortcomings. All attributes and methods of this single object are common and can be accessed and modified externally at any time. Therefore, the closure is used to simulate private attributes and methods, as shown below:

mySpace.Singleton=(function(){  var privateAttribute1=false;  var privateAttribute1=[1,2,3];  function privateMethod1(){  }  function privateMethod2(){  }  return {  publicAttribute1:true,  publicAttribute2:10,  publicMethod1:function(){    privateAttribute1=true;    privateMethod1();  },  publicMethod2:function(arg){    privateAttribute1=[4,5,6];    privateMethod2();  }  }})();


Here, we assign an anonymous self-executed function to this single object. In this function, we use the var and function keywords to define their private attributes and methods, respectively, these cannot be directly accessed outside the function (outside the single object), because as soon as the function is executed, the space in its internal scope will be recycled, this is why the closure can be used to simulate private attributes and methods. In this function (closure), an object is returned at the same time. This object contains some public methods and attributes that can be directly called externally. At the same time, these public methods are defined inside the function, therefore, you can call its private attributes and methods. However, the public methods and properties returned by the outside world can only be used to complete some operations. You cannot directly call Singleton. privateMethod1 attributes. This allows the single object to isolate the external to directly access its private attributes and methods, and provide some common attributes and methods to the external to complete some operations.

This standalone mode constructed by self-execution of anonymous functions is widely used in many js libraries, but there is still a problem. If we do not need to use this object when loading pages, in addition, it is costly to create an object (for example, to perform a large amount of computing or to access the dom tree and Its Attributes multiple times). It is reasonable to create an object when necessary, instead of directly creating it with the parsing execution of js, this concept is called lazy loading. Therefore, modify the above Code as follows:

mySpace.Singleton=(function(){    var uniqueInstance;    function constructor(){      var privateAttribute1=false;      var privateAttribute1=[1,2,3];      function privateMethod1(){      }      function privateMethod2(){      }      return {        publicAttribute1:true,        publicAttribute2:10,        publicMethod1:function(){          privateAttribute1=true;          privateMethod1();        },        publicMethod2:function(arg){          privateAttribute1=[4,5,6];          privateMethod2();        }      }    }    return {      getInstance:function(){       if(!uniqueInstance){         uniqueInstance=constructor();       }        return uniqueInstance;      }    }  })();

First, a private variable uniqueInstance is defined in the anonymous function as a handle to determine whether a single object is created, then, put all the attributes and methods defined for the single object in a function named constructor. Only when this function is called will this single object be created. Otherwise, it will not be created directly. Then, an object is returned, which contains a getInstance Method for external calls. When calling this method, the system first checks whether the single object exists. If yes, it is returned directly, otherwise, call the constructor function to construct the single object and return it. Finally, if we call a method of this single object, we need to use mySpace. singleton. getInstance (). publicMethod1 (). Here, this single object is created only when we call it in this way. Otherwise, this single object will not be automatically created, this actually achieves On-Demand Loading or inert loading.

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.