Home > Article > Web Front-end > JavaScript singleton pattern concepts and code examples
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.
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.
The demo address is: Pop-up box example
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
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)!