Preface
Like other programming languages, Javascript also has many design patterns, such as singleton mode, proxy mode, observer mode, etc. Proficient use of Javascript design patterns can make our code logic clearer and easier to maintain and refactor.
This article will introduce the more common and practical mode in Javascript mode - singleton mode, which is mainly divided into concept and example parts. While introducing examples, additional knowledge points in the code will also be explained.
Concept of singleton pattern
First of all, what is singleton pattern? It can be understood this way: the singleton pattern aims to ensure that a class has only one instance and provides a global access point.
Maybe some people still don’t understand the concept of singleton, so you can imagine some examples in life. For example, when registering an account, if the account we registered already exists, the system will prompt us "The account already exists. Do you want to use this account to log in?". We cannot create an identical account again unless we cancel the original account. This is a vivid embodiment of the singleton pattern.
A similar example is the login pop-up box on the web page. No matter how many times we click the login button, only one login pop-up box will always be displayed on the interface, and a second one cannot be created.
This article will take the login pop-up box as an example to introduce the use of singleton mode.
Single case mode example
1.demo display
The demo address is: Pop-up box example
2. Code display
The code to build a singleton mode pop-up box instance may be written differently by everyone, but the purpose is the same: to build a globally unique and accessible pop-up box. Next we implement this example step by step.
(1) Obtain the DOM object
var $ = function(id) { return typeof id === 'string' ? document.getElementById(id) : id; };
First of all, in order to facilitate some subsequent operations on the DOM, we will use the principle of functional programming to obtain the element object of the target id. The method is encapsulated and can be obtained directly using $(id).
(2) Pop-up frame constructor
var Modal = function(id, html) { this.html = html; this.id = id; this.open = false; };
Here we declare a Modal as the constructor of the pop-up frame, and define the public attributes html and id inside it and open. HTML is used to define the content inside the pop-up box, id is used to define the id name for the pop-up box, and open is used to determine whether the pop-up box is open.
(3) open method
Modal.prototype.create = function() { if (!this.open) { var modal = document.createElement('p'); modal.innerHTML = this.html; modal.id = this.id; document.body.appendChild(modal); setTimeout(function() { modal.classList.add('show'); }, 0); this.open = true; } };
We defined the create method on the prototype chain of Modal. Inside the method, we create and insert the bullet box into the DOM, and at the same time give Add an animation effect with class "show" to the pop-up box. Here is a brief introduction to classList:
classList is a more convenient attribute to operate the element class than className, but it is not compatible with versions below IE10 in terms of compatibility:
The operation class methods it provides are similar to those of jQuery, mainly
add(class1, class2, ...) Add one or more class names to the element, similar to jQuery's addClass ()
remove(class1, class2, …) Removes one or more class names from the element, similar to jQuery’s removeClass()
contains(class) Determines whether the specified class name exists, similar to jQuery's hasClass()
Here we use the add method to add the show class to Modal.
(4) close method
Modal.prototype.delete = function() { if (this.open) { var modal = $(this.id); modal.classList.add('hide'); setTimeout(function() { document.body.removeChild(modal); }, 200); this.open = false; } };
After defining the open method, we define here a method to close the pop-up box, and add a hide class animation effect to the pop-up box object inside it. , and finally remove the pop-up object from the page.
(5) Create an instance
var createIntance = (function() { var instance; return function() { return instance || (instance = new Modal('modal', '这是一个弹框')) } })();
This is an important part of implementing the singleton mode. Let’s analyze the knowledge points:
-
Use ClosureEncapsulates the instance private variable and returns a function
Use || syntax to determine if the instance does not exist, execute the latter's instantiation Modal If the method exists, it will directly return instance, ensuring that there is only one pop-up instance
The creation of this instance can also be understood as part of the proxy mode.
(6) Button operation
var operate = { setModal: null, open: function() { this.setModal = createIntance(); this.setModal.create(); }, delete: function() { this.setModal ? this.setModal.delete() : ''; } };
Here we put the button operation in the operate object, so that the opening and closing operations can obtain the instance setModal through this.
(7) Binding events
$('open').onclick = function() { operate.open(); }; $('delete').onclick = function() { operate.delete(); };
Finally, we bind the open and delete methods to the two buttons. At this point, we use the singleton mode to implement the pop-up box The demo is implemented.
Please view the complete code: Complete code
Conclusion
The above is the content of the JavaScript singleton mode concept and code examples. For more related content, please pay attention to the PHP Chinese website (www .php.cn)!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version
SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version
Useful JavaScript development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
