PrefaceToday, I was reviewing the creational pattern in the design pattern and found that there are many ways to implement the singleton pattern in JS. I summarized them briefly and listed the following 6 ways to share with you. Generally speaking, the content is divided into two parts: ES5 (Function) and ES6 (Class) implementation. The concept of singleton patternThe singleton pattern is to save an instance in the system, which is a global variable. In team development, in order to achieve some similar functions, such as form validation between different pages, the requirements may be different, but the names may be the same, then there will be conflicts. At this time, the singleton pattern can solve this problem well.
Talk about its advantages: 1. The singleton pattern declares a namespace, which generates a unique global variable, a namespace, which can be declared in the same way as an object declaration:
Have you found that this is a bit similar to an object? In fact, name and init are its properties. You can get the value of its name through mapleTao.name, and call the init method through mapleTao.init(). In this way, when dealing with multiple demand pages and multi-person development, you can solve the problem of naming conflicts well, and you can better maintain and control the code. 2. The singleton mode only declares one variable in the global state. As we all know, in js, if you write a method, such as function aa(){}, a variable called aa will be generated in the window. When a function is implemented, many functions will be created in the code encapsulation. In this way, many variables will be created in the window, which will occupy more memory units. The scope of global variables is very wide and may change in many processing functions. In this way, it is not easy to find bugs quickly when they occur. However, the object variables created by the singleton mode can find problems more quickly and solve them, which greatly reduces the time for problem repair and system loading. 3. It has more advantages in terms of memory and resource usage than creating new objects by new when implementing the same function. Method 1Use instanceof to determine whether to use the new keyword to call a function to instantiate an object function User() { if (!(this instanceof User)) { return } if (!User._instance) { this.name = 'Unnamed' User._instance = this } return User._instance } const u1 = new User() const u2 = new User() console.log(u1===u2); // true Method 2Add method attribute call directly to the function to generate an instance function User(){ this.name = 'Unnamed' } User.getInstance = function(){ if(!User._instance){ User._instance = new User() } return User._instance } const u1 = User.getInstance() const u2 = User.getInstance() console.log(u1===u2); Method 3Using closures, improved method 2 function User() { this.name = 'Unnamed' } User.getInstance = (function () { var instance return function () { if (!instance) { instance = new User() } return instance } })() const u1 = User.getInstance() const u2 = User.getInstance() console.log(u1 === u2); Method 4Implemented using wrapper objects combined with closures const User = (function () { function _user() { this.name = 'xm' } return function () { if (!_user.instance) { _user.instance = new _user() } return _user.instance } })() const u1 = new User() const u2 = new User() console.log(u1 === u2); // true Of course, the closure code can be encapsulated as a function When singletons are frequently used, it is recommended to use a solution similar to this method. Of course, the internal implementation can use any of the above methods. function SingleWrapper(cons) { // Exclude non-functions and arrow functions if (!(cons instanceof Function) || !cons.prototype) { throw new Error('Not a legal constructor') } var instance return function () { if (!instance) { instance = new cons() } return instance } } function User(){ this.name = 'xm' } const SingleUser = SingleWrapper(User) const u1 = new SingleUser() const u2 = new SingleUser() console.log(u1 === u2); Method 5Use new.target in the constructor to determine whether to use the new keyword class User{ constructor(){ if(new.target !== User){ return } if(!User._instance){ this.name = 'xm' User._instance = this } return User._instance } } const u1 = new User() const u2 = new User() console.log(u1 === u2); Method 6Using static methods class User { constructor() { this.name = 'xm' } static getInstance() { if (!User._instance) { User._instance = new User() } return User._instance } } const u1 = User.getInstance() const u2 = User.getInstance() console.log(u1 === u2); SummarizeThis is the end of this article about JS implementation of the singleton pattern. For more relevant JS singleton pattern content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Solution to index failure in MySQL due to different field character sets
>>: Detailed explanation of mysql execution plan id is empty (UNION keyword)
Nginx (engine x) is a lightweight, high-performan...
Preface In MySQL, both Innodb and MyIsam use B+ t...
Table of contents Overview Functionality and read...
Table of contents Overview Solution 1: Closures S...
This article shares the installation and configur...
Considering that many people now use smartphones, ...
Install FFmpeg flac eric@ray:~$ sudo apt install ...
After configuring the tabBar in the WeChat applet...
Database Table A: CREATE TABLE task_desc_tab ( id...
1. It is preferred to use the root user to log in...
Preface Only Innodb and MyISAM storage engines ca...
Table of contents Stabilization Introduction Anti...
Table of contents 0x01. Install the Pagoda Panel ...
Basic Introduction to Floating In the standard do...
Table of contents 1 View the current database con...