Home  >  Article  >  Web Front-end  >  Sharing the implementation of single mode in JavaScript_javascript skills

Sharing the implementation of single mode in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:17:13837browse

Single mode as a software development model has been widely used in many object-oriented languages. In JavaScript, the single mode is also very widely used. However, because the JavaScript language has its unique object-oriented approach, it leads to 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 look at the definition of singleton pattern in traditional object-oriented languages: Singleton pattern is a class that can only be instantiated once and can be accessed through a well-known access point. There are two points in this definition that highlight the characteristics of traditional object-oriented languages, namely classes and instantiations. Therefore, for traditional object-oriented languages, the singleton mode is based on the natural characteristics of its classes and instantiations, that is, using key The word class defines a class, which can be instantiated through the new keyword, but it needs to be ensured that the same instance is obtained each time it is instantiated by new, or its constructor can only be called once through new.

Let’s take a look at the definition of singleton mode in JavaScript: A singleton is an object used to divide the namespace and organize a group of related methods and properties together. If it can be instantiated, it can only be instantiated. melt once. Comparing the above definition, you will find that the single definition here essentially defines it as an object, rather than a class in a traditional object-oriented language. This also shows that the JavaScript language is based on objects. At the same time, it was pointed out later that if it can be instantiated, this shows that there should be several ways to define a single object in JavaScript. There are one or several ways to create a single object by using the new keyword. However, this method is not a natural feature of JavaScript itself, because objects created using the new keyword actually use function to simulate the definition of its constructor (although ES6 has begun to support the class keyword, it has not yet been viewed (Widely supported by all browsers)), so how to use the natural features of JavaScript to implement the singleton mode?

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

  },
  method2:function(arg){

  }
}

An object Singleton is defined here, which contains several properties and methods. It is included in the page. This object is created when js is loaded. When calling, use Singleton.method1 to call it. Its instantiation is As the page is loaded and the js parsing and execution process is completed, we do not use the new keyword to instantiate this object. This is also a big difference between the implementation of the single mode in JavaScript and traditional object-oriented languages. This way is simpler and easier to understand. However, this method has several shortcomings. One obvious shortcoming is that it does not provide a namespace. If other programmers also define a Singleton variable in the page, it is easy to rewrite and confuse the single object, so 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 the Singleton object under this object. This greatly reduces the possibility of conflicts and misoperations with other programmers, even if others are in the global scope. Defining a Singleton variable will not pollute the single object. This achieves the function of dividing the namespace and organizing some related properties and methods together as mentioned in the previous definition.

This method still has shortcomings. All properties and methods of this single object are common and can be accessed and modified by the outside at any time. Therefore, closures are 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 self-executing function to the single object. In this function, we use the var and function keywords to define its private properties and methods respectively. These cannot be directly accessed outside the function (outside the single object). Accessible, because as soon as the function is executed, the space in its internal scope will be reclaimed, which is why closures can be used to simulate private properties and methods. In this function (closure), an object is finally returned. This object contains some public methods and properties, which can be called directly from the outside. At the same time, because these public methods are defined inside the function, their private properties and methods can be called. However, the outside world can only complete certain operations through the returned public methods and properties, and cannot directly call Singleton.privateMethod1 properties. This allows the single object to not only isolate the outside world from directly accessing its private properties and methods, but also provide some common properties and methods to the outside world to complete certain operations.

This singleton mode constructed by anonymous function self-execution is widely used in many js libraries, but there is still a problem. If we do not need to use the object when loading the page, and the object When it is expensive to create (such as requiring a lot of calculations or multiple accesses to the DOM tree and its properties, etc.), a reasonable approach is to create it when you need it, rather than creating it directly with the parsing and execution of js. This This concept is called lazy loading, so the above code is modified 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 single object has been created, and then put all the properties and methods just defined for the single object into a constructor. In the function, the single object will be created only when the function is called, otherwise it will not be created directly. Then, an object is returned, which contains a getInstance method. This method is for external calls. When calling this method, first determine whether the single object exists. If it exists, return it directly. Otherwise, call the constructor function to construct the single object. Return to it again. Finally, if we call a method of the single object, we need to use mySpace.Singleton.getInstance().publicMethod1(). Here, the single object will be created only when we call it like this, otherwise the single object will not be created. will be automatically created, which actually implements on-demand loading or lazy loading.

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