Home > Article > Web Front-end > Javascript singleton pattern
This time I will bring you the single case mode of Javascript, what are the precautions of Javascript singleton mode, the following is a practical case, let’s take a look.
The singleton pattern is an object used to divide the namespace and organize a batch of properties and methods together. If it can be instantiated, then it Can only be instantiated once.
Divide the namespace and reduce global variables
Organize the code into one for easy reading and maintenance
Not all object literals are singletons, such as simulated data
Basic structure:
let Cat = { name: 'Kitty', age: 3, run: ()=>{ console.log('run'); } }
The above object literal structure is one of the ways to create a singleton mode, but it is not a singleton mode. The characteristic of the singleton mode is that it is only instantiated once
To implement the singleton mode, you can use variables to indicate whether the class is instanced.
Basic implementation:
class Singleton { constructor(name){ this.name = name; this.instance = null; } getName(){ return this.name; }}let getInstance = (()=> { let instance; return (name)=> { if(!instance) { instance = new Singleton(name); } return instance; }})()let cat1 = getInstance('Hello');let cat2 = getInstance('Kitty');console.log(cat1 === cat2); //trueconsole.log(cat1.getName()) //'Hello'console.log(cat2.getName()) //'Hello'
Use the instance variable to indicate the instance Singleton. If there is no instance, create one. If there is, directly Return the instance. Since it can only be instantiated once, the instance obtained by cat2 is the same as cat1
Practical
In order to avoid repeated creation when creating DOM elements, you can use the singleton mode to create
//单例模式let createModal = function() { let content = document.createElement('div'); content.innerHTML = '弹窗内容'; content.style.display = 'none'; document.body.appendChild(content); }//代理获取实例let getInstance = function(fn) { let result return function() { return result || (result = fn.call(this,arguments)); } }let createSingleModal = getInstance(createModal);document.getElementById("id").onclick = function(){ let modal = createSingleModal(); modal.style.display = 'block'; };
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:
The above is the detailed content of Javascript singleton pattern. For more information, please follow other related articles on the PHP Chinese website!