1. Understand the singleton mode
Definition of singleton mode: Ensure that a class has only one instance and provide a global access point to access it
Singleton mode The core: to ensure that there is only one instance and provide global access
2. Singleton mode in JavaScript
In js, we often use global variables as singleton mode. For example:
var a={};
Why a can be used as a global variable, because it meets the following two conditions:
1. Object a is unique
2. a is defined in the global scope, providing global access
Note: However, it is recommended to use namespaces in js to reduce the number of global variables
3. Lazy singleton
Lazy singleton: an object instance created only when needed
Purpose: There are two buttons on the page. When clicked, a response pop-up window needs to be displayed and Load the corresponding css file
Note: Some developers are used to writing in the page when it loads, and then setting the hidden state, which will waste DOM nodes
The following is the implementation code:
1. Main page
2. p1.css
/** * Description: * Created by wxy on 2018/2/13 11:02 */ #p2{ width: 500px; height: 300px; background: #ffdd00; color: #fff; position: fixed; top: 50%; left: 50%; transform: translate(-50%,-50%); } #closep2{ cursor: pointer; margin-right: 5px; margin-top: 5px; float: right; border: 1px solid #fff; }
3. p2.css
/** * Description: style of p1 * Created by wxy on 2018/2/13 11:01 */ #p1{ width: 500px; height: 300px; background: #0b0a0a; color: #fff; position: fixed; top: 50%; left: 50%; transform: translate(-50%,-50%); } #closep1{ cursor: pointer; margin-right: 5px; margin-top: 5px; float: right; border: 1px solid #fff; }
Related recommendations:
Two options for js singleton mode_javascript skills
Summary of NodeJS singleton mode, adapter mode, decoration mode, and observer mode
js Singleton Pattern Detailed Example_Basic Knowledge
The above is the detailed content of js singleton mode to create pop-up window instance sharing. For more information, please follow other related articles on the PHP Chinese website!