定义
**是允许实例化一次的对象类,**<br /> 有时我们也用一个对象来规划一个命名空间
demo
不透明的
let Singleton = (function(){ // 确保单利引入 var instance = null; class CreateSingleton{ constructor(name){ this.name = name; if(instance){ return instance; } instance = this; } getName() { console.log(this.name) } } return CreateSingleton;})();// 创建实例对象1let a = new Singleton('a');// 创建实例对象2let b = new Singleton('b');console.log(a.name);console.log(a === b);
透明的
class CreateSingleton{ constructor(name){ this.name = name; } getName() { console.log(this.name) }}let Singleton = (function () { let instance = null; return function (name) { if(!instance){ instance = new CreateSingleton(name) } return instance }})();
惰性单例模式
**只有当触发创建实例对象时,实例对象才会被创建。**
抽取单例
function singleton (fn) { let instance = null; return function () { // 可以用类的安全方法来使用方法调用 return instance || (instance = fn.apply(this,arguments)) }}
创建遮罩层
let createMask = function(){ // 创建div元素 let mask = document.createElement('div'); // 设置样式 mask.style.position = 'fixed'; mask.style.top = '0'; mask.style.right = '0'; mask.style.bottom = '0'; mask.style.left = '0'; mask.style.opacity = 'o.75'; mask.style.backgroundColor = '#000'; mask.style.display = 'none'; mask.style.zIndex = '98'; document.body.appendChild(mask); // 单击隐藏遮罩层 mask.onclick = function(){ this.style.display = 'none'; }; return mask;};
创建登陆窗口
var createLogin = function() { // 创建div元素 var login = document.createElement('div'); // 设置样式 login.style.position = 'fixed'; login.style.top = '50%'; login.style.left = '50%'; login.style.zIndex = '100'; login.style.display = 'none'; login.style.padding = '50px 80px'; login.style.backgroundColor = '#fff'; login.style.border = '1px solid #ccc'; login.style.borderRadius = '6px'; login.innerHTML = 'login it'; document.body.appendChild(login); return login;};
设置触发事件
document.getElementById('btn').onclick = function() { var oMask = singleton(createMask)(); oMask.style.display = 'block'; var oLogin = singleton(createLogin)(); oLogin.style.display = 'block'; var w = parseInt(oLogin.clientWidth); var h = parseInt(oLogin.clientHeight);};