Home Web Front-end JS Tutorial Detailed explanation of the steps to implement singleton mode in JS

Detailed explanation of the steps to implement singleton mode in JS

Apr 14, 2018 am 09:25 AM
javascript model Detailed explanation

This time I will bring you a detailed explanation of the steps to implement single case mode in JS. What are the precautions for JS to implement singleton mode. The following is a practical case. Let’s take a look. one time.

Traditional Singleton Pattern

Ensure there is only one instance of a class and provide a global access point to it.

Implementing the core idea of ​​singleton

It is nothing more than using a variable to mark whether an object has been created for a certain class. If so, the next time an instance of the class is obtained, the previously created object will be returned directly. Next, we use JavaScript to To forcefully implement this idea, please see the code:

var Singleton = function( name ){
  this.name = name;
};
Singleton.prototype.getName = function(){   alert ( this.name );
};
Singleton.getInstance = (function(){   var instance = null;
  return function( name ){
          if ( !instance ){
            instance = new Singleton( name );
          }
        return instance;       }
})();
Copy after login

We use Singleton.getInstance to obtain the only object of the Singleton class. This is indeed no problem, but js itself does not have the concept of a class, so it makes no sense for us to implement it with traditional singleton ideas. Such code It's smelly and long (actually I feel uncomfortable looking at it). Below we use JavaScript's closure to implement a singleton, please see the code:

var Createp = (function(){       var instance;
      var Createp = function( html ){           if ( instance ){
            return instance;           }
          this.html = html; this.init();
          return instance = this;
};
Createp.prototype.init = function(){
var p = document.createElement( 'p' );
p.innerHTML = this.html; 
document.body.appendChild( p );
      };
      return Createp; })();
var a = new Createp( 'sven1' ); var b = new Createp( 'sven2' );
alert ( a === b ); // true
Copy after login

As you can see, we have indeed used closures to implement a singleton, but this code is still highly coupled. Createp's constructor is actually responsible for two things. The first is to create the object and execute the initialization init method, and the second is to ensure that there is only one object. Such code has unclear responsibilities. Now we have to separate these two tasks. The constructor is responsible for constructing the object. As for judging whether to return an existing object or construct a new object and return it, we leave it to another function to complete. In fact, it is to satisfy a programming idea: the single responsibility principle. This kind of code can be better decoupled, please see the following code:

var Createp = function (html) {
    this.html = html;
    this.init();
  };
  Createp.prototype.init = function () {
    var p = document.createElement('p');
    p.innerHTML = this.html;
    document.body.appendChild(p);
  };
  var ProxySingletonCreatep = (function () {
    var instance;
    return function (html) {
      if (!instance) {
        instance = new Createp(html);
      }
      return instance;
    }
  })();
  var a = new ProxySingletonCreatep('sven1');
  var b = new ProxySingletonCreatep('sven2');
  alert(a === b); //true
Copy after login

As you can see, our constructor Createp is now only responsible for constructing objects. As for whether to return an existing object or construct a new object and return it, we leave this matter to the proxy class proxySingletonCreatep. This kind of code is comfortable to look at. (zhuang) obey (bi)!

Finally, post a highly abstract singleton pattern code, the essence of lazy singleton!

//单例模式抽象,分离创建对象的函数和判断对象是否已经创建
  var getSingle = function (fn) {
    var result;
    return function () {
      return result || ( result = fn.apply(this, arguments) );
    }
  };
Copy after login

The formal parameter fn is our constructor. We only need to pass in any constructor we need to generate a new lazy singleton. For example, if you pass in the constructor to create a girlfriend and call getSingle(), you can generate a new girlfriend. If you call getSingle() in the future, only the girlfriend you just created will be returned. As for a new girlfriend - she doesn't exist.

Singleton common scenarios

When you only need to generate a unique object, such as a page login box, there can only be one login box, then you can use the singleton idea to implement it. Of course, you don’t have to use the singleton idea to implement it. That will bring The result may be that you have to regenerate and display a login box every time you want to display the login box (consuming performance), or you may accidentally display two login boxes.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to operate the case conversion of the first letter when Jackson parses a json string

localstorage and sessionstorage How to use

in Vue

The above is the detailed content of Detailed explanation of the steps to implement singleton mode in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What does WeChat's Do Not Disturb mode do? What does WeChat's Do Not Disturb mode do? Feb 23, 2024 pm 10:48 PM

What does WeChat Do Not Disturb mode mean? Nowadays, with the popularity of smartphones and the rapid development of mobile Internet, social media platforms have become an indispensable part of people's daily lives. WeChat is one of the most popular social media platforms in China, and almost everyone has a WeChat account. We can communicate with friends, family, and colleagues in real time through WeChat, share moments in our lives, and understand each other’s current situation. However, in this era, we are also inevitably faced with the problems of information overload and privacy leakage, especially for those who need to focus or

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Do Not Disturb Mode Not Working in iPhone: Fix Do Not Disturb Mode Not Working in iPhone: Fix Apr 24, 2024 pm 04:50 PM

Even answering calls in Do Not Disturb mode can be a very annoying experience. As the name suggests, Do Not Disturb mode turns off all incoming call notifications and alerts from emails, messages, etc. You can follow these solution sets to fix it. Fix 1 – Enable Focus Mode Enable focus mode on your phone. Step 1 – Swipe down from the top to access Control Center. Step 2 – Next, enable “Focus Mode” on your phone. Focus Mode enables Do Not Disturb mode on your phone. It won't cause any incoming call alerts to appear on your phone. Fix 2 – Change Focus Mode Settings If there are some issues in the focus mode settings, you should fix them. Step 1 – Open your iPhone settings window. Step 2 – Next, turn on the Focus mode settings

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

Detailed explanation of Linux curl command Detailed explanation of Linux curl command Feb 21, 2024 pm 10:33 PM

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

See all articles