const Singleton = (function() {
let instance = null;
return function() {
if (!instance) {
instance = new Noraml();
}
return instance;
};
})();
let SO1 = new Singleton();
SO1.count++;
let SO2 = new Singleton();
console.log(SO1.count);//1
console.log(SO2.count);//1
console.log(SO1.count === SO2.count);//true
//兩個是一樣的物件
//流程
//按下按鈕時,去呼叫這個class的 function
//於此同時會去判斷是否被實體化
//如果還沒,就返回一個new的實體化
//如果已經,就返回實體化的物件
<button id="loginBtn">登录</button>
<script>
const btn = document.getElementById('loginBtn');
btn.addEventListener('click', function() {
loginLayer.getInstance();
}, false);
class loginLayer {
constructor() {
this.instance = null;
this.init();
}
init() {
var div = document.createElement('div');
div.classList.add('login-layer');
div.innerHTML = "我是登录浮窗";
document.body.appendChild(div);
}
static getInstance() {
if(!this.instance) {
this.instance = new loginLayer();
}
return this.instance;
}
}
//export 模式 for node
class Singleton {
constructor () {
if (!Singleton.instance) {
Singleton.instance = this
}
// Initialize object
return Singleton.instance
}
// Properties & Methods
}
const instance = new Singleton()
Object.freeze(instance)
export default instance