


In-depth understanding of JavaScript series (25): Detailed explanation of the singleton pattern of design patterns_Basic knowledge
Introduction
Starting from this chapter, we will gradually introduce the implementation of various design patterns used in JavaScript. Here I will not introduce too much about the theory of the pattern itself, but will only focus on the implementation. OK, it’s officially started.
In the eyes of traditional development engineers, a singleton is to ensure that a class has only one instance. The implementation method is generally to first determine whether the instance exists. If it exists, return it directly. If it does not exist, create it and return it. This ensures A class has only one instance object. In JavaScript, a singleton acts as a namespace provider, providing a unique access point to the object from the global namespace.
Text
In JavaScript, there are many ways to implement singletons. One of the simplest ways is to use object literals, which can contain a large number of properties and methods:
var mySingleton = {
Property1: "something",
Property2: "something else",
Method1: function () {
console.log('hello world');
}
};
If you later extend this object, you can add your own private members and methods, and then use closures to encapsulate these variable and function declarations inside it. Expose only the public members and methods you want to expose. The sample code is as follows:
var mySingleton = function () {
/* Declare private variables and methods here */
var privateVariable = 'something private';
Function showPrivate() {
console.log(privateVariable);
}
/* Public variables and methods (private variables and methods can be accessed) */
Return {
publicMethod: function () {
showPrivate();
},
publicVar: 'the public can see this!'
};
};
var single = mySingleton();
single.publicMethod(); // Output 'something private'
console.log(single.publicVar); // Output 'the public can see this!'
The above code is very good, but what if we want to initialize it only when it is used? In order to save resources, we can initialize these codes in another constructor, as follows:
var Singleton = (function () {
var instantiated;
Function init() {
/*Define singleton code here*/
return {
publicMethod: function () {
console.log('hello world');
},
publicProperty: 'test'
};
}
return {
getInstance: function () {
if (!instantiated) {
instantiated = init();
}
return instantiated;
}
};
})();
/*Call public methods to get instances:*/
Singleton.getInstance().publicMethod();
We now know how to implement a singleton, but in what scenarios is a singleton best used? In fact, singletons are generally used to coordinate various modes of communication between systems. The following code is a best practice for a singleton:
var SingletonTester = (function () {
//Parameters: a set of parameters passed to the singleton
Function Singleton(args) {
//Set the args variable to the received parameters or empty (if not provided)
var args = args || {};
//Set the name parameter
This.name = 'SingletonTester';
//Set the value of pointX
This.pointX = args.pointX || 6; //Get it from the received parameters, or set it to the default value
//Set the value of pointY
This.pointY = args.pointY || 10;
}
//Instance container
var instance;
var _static = {
name: 'SingletonTester',
//Method to get the instance
//Return Singleton instance
getInstance: function (args) {
If (instance === undefined) {
instance = new Singleton(args);
}
return instance;
}
};
Return _static;
})();
var singletonTest = SingletonTester.getInstance({ pointX: 5 });
console.log(singletonTest.pointX); // Output 5
Other implementation methods
Method 1:
function Universe() {
// Determine whether an instance exists
If (typeof Universe.instance === 'object') {
return Universe.instance;
}
// Other content
This.start_time = 0;
This.bang = "Big";
// Cache
Universe.instance = this;
// Implicitly returns this
}
//Test
var uni = new Universe();
var uni2 = new Universe();
console.log(uni === uni2); // true
Method 2:
function Universe() {
// cached instance
var instance = this;
// Other content
This.start_time = 0;
This.bang = "Big";
// Override constructor
Universe = function () {
return instance;
};
}
//Test
var uni = new Universe();
var uni2 = new Universe();
uni.bang = "123";
console.log(uni === uni2); // true
console.log(uni2.bang); // 123
Method 3:
function Universe() {
// Cache instance
var instance;
// Reconstructor function
Universe = function Universe() {
return instance;
};
// Post-processing prototype properties
Universe.prototype = this;
// Example
Instance = new Universe();
// Reset constructor pointer
Instance.constructor = Universe;
// Other functions
Instance.start_time = 0;
Instance.bang = "Big";
return instance;
}
// Test
var uni = new Universe();
var uni2 = new Universe();
console.log(uni === uni2); // true
//Add prototype attributes
Universe.prototype.nothing = true;
var uni = new Universe();
Universe.prototype.everything = true;
var uni2 = new Universe();
console.log(uni.nothing); // true
console.log(uni2.nothing); // true
console.log(uni.everything); // true
console.log(uni2.everything); // true
console.log(uni.constructor === Universe); // true
Method 4:
var Universe;
(function () {
var instance;
Universe = function Universe() {
if (instance) {
return instance;
}
instance = this;
// Other content
This.start_time = 0;
This.bang = "Big";
};
} ());
//Test code
var a = new Universe();
var b = new Universe();
alert(a === b); // true
a.bang = "123";
alert(b.bang); // 123

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use