_javascript techniques for single mode sharing in JavaScript

Source: Internet
Author: User
Tags closure

As a software development model, monomer mode has been widely used in many object-oriented languages, and the monomer mode is widely used in JavaScript, but because JavaScript language has its own unique object-oriented way, It is consistent with some traditional object-oriented language although it is in the unitary mode, but it is different in the realization.

First, look at the traditional object-oriented language for the definition of the monomer pattern: The singleton pattern is a class that can only be instantiated once and accessible through a well-known access point. This definition has two points highlighting the characteristics of the traditional object-oriented language, class and instantiation, so for the traditional object-oriented language, the monomer pattern is based on its class and instantiated natural characteristics, that is, using the keyword class to define a class that can be instantiated by the new keyword. However, it is necessary to ensure that each time the new is instantiated, it is given the same instance, or the constructor function can only be called by new.

Let's look at the definition of the monomer pattern in javascript: A monomer is an object that is used to partition a namespace and organize a group of related methods and attributes together, and if it can be instantiated, it can only be instantiated once. In contrast to the above definition, you will find that the monomer definition here defines its substance as an object rather than a class in the traditional object-oriented language, which suggests that the language of JavaScript is object-based. It also follows that, if instantiated, this suggests that there should be several ways in which the monomer definition in JavaScript exists, one or several ways in which you can instantiate a single object using the New keyword, but this is not a natural feature of JavaScript itself. Because objects created with the New keyword actually simulate the definition of their constructors by function (although ES6 is beginning to support class keywords, it has not been widely supported by browsers). So how do you use the natural features of JavaScript to implement the singleton model?

var singleton={
  attribute1:true,
  attribute2:10,
  method1:function () {

  },
  method2:function (ARG ){

  }
}

This defines an object singleton, which contains several properties and methods, which are included in the page, and the object is created when JS is loaded. Invoked using SINGLETON.METHOD1, the instantiation is done as the page is loaded into the JS parsing execution, and we do not instantiate the object using the New keyword, which is a big difference between the implementation of the singleton pattern and the traditional object-oriented language in JavaScript. This approach is simpler and easier to understand. However, there are several drawbacks to this approach, one obvious drawback is that it does not provide namespaces, other programmers if the page also defines a singleton variable, so it is easy to rewrite and confuse the monomer object, so to address this issue, rewrite it as follows:

var myspace={};
myspace.singleton={
  attribute1:true,
  attribute2:10,
  method1:function () {

  },
  method2: Function (ARG) {

  }
}


This first defines a MySpace namespace and then mounts the monomer object singleton underneath the object, which greatly reduces the likelihood of conflicts and misoperation with other programmers, even if others define a singleton variable in the global scope. Nor does it contaminate the monomer object, which implements the function of partitioning the namespace as described in the preceding definition and organizing some related properties and methods together.

This method is still flawed, all the properties and methods of this monomer object are common, and can be accessed and modified externally at any time, so the closure is used to simulate private properties and methods, as follows:

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 directly assign an anonymous function to the monomer object, in which the Var and function keywords are used to define their private properties and methods, which are not directly accessible outside the function (the monomer object), because once the function is executed, The space for its internal scope is reclaimed, which is why the closure can be used to simulate private properties and methods. In this function (the closure), at the same time, it eventually returns an object that contains public methods and properties, which can be called directly externally, and can call private properties and methods because they are defined inside the function, but the outside can only do something by returning public methods and properties. It is not possible to call singleton.privatemethod1 these properties directly. This allows the monomer object to isolate the outside world to directly access its private properties and methods, and to provide some common properties and methods to complete some operations.

This kind of anonymous function is constructed by the monomer pattern in many JS libraries is widely used, however, there is still a problem, if we do not need to use the object when loading the page, and the creation of the object is expensive (if you need to do a lot of computing or need to access the DOM tree and its properties many times), It is reasonable to create it when you need it, instead of creating it directly with the parsing of JS, which is called lazy loading (lazy loading), so 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}
      }

  ) ();

Here we first define a private variable uniqueinstance in the anonymous function as a handle to determine whether the monomer object was created, and then put all the properties and methods defined on the singleton object in a function named constructor, which is called only by the function. will create the monomer object, otherwise it will not be created directly. Then, an object is returned that contains a getinstance method, which is for external invocation, when the method is invoked to first determine whether the monomer object exists, if it exists, to return it directly, otherwise call the constructor function to construct the monomer object and return it. Finally, if we call a method of the singleton object, we need to use MySpace.Singleton.getInstance (). PUBLICMETHOD1 (), here, this monomer object is created only when we call this. Otherwise, the monomer object is not automatically created, which actually implements on-demand loading or lazy 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.