如果先创建,等需要的时候弹出是浪费资源的。
如果等点登录按钮创建,关闭再删除,再点击创建,关闭删除,非常耗费内存。
这样就可以用到前面的单例模式,进行判断,如果没有就创建,有了就直接用。
按需创建的单例模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| <!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> body { background-color: #f0f0f0; }
#loginLayer { position: absolute; left: 240px; top: 80px; 200px; height: 200px; border: 1px solid #ccc; background-color: #fff; text-align: center; }
#maskLayer { position: absolute; left: 0; top: 0; 100%; height: 100%; background-color: #000; opacity: 0.3; } </style> </head>
<body> <button id="loginBtn">登录</button> <!-- <div id="loginLayer">登录窗口</div> <div id="maskLayer"></div> -->
<script> var createLoginLayer = (function () { var loginLayer =null;
return function () { 大专栏 登录框-使用惰性生成 if (!loginLayer) { loginLayer = document.createElement("div"); loginLayer.id = "loginLayer"; loginLayer.innerHTML = "登录窗口"; loginLayer.style.display = "none"; document.body.appendChild(loginLayer); } return loginLayer; }; })();
var createMaskLayer = (function () { var maskLayer =null;
return function () { if (!maskLayer) { maskLayer = document.createElement("div"); maskLayer.id = "maskLayer"; maskLayer.innerHTML = "登录窗口"; maskLayer.style.display = "none"; document.body.appendChild(maskLayer); } return maskLayer; }; })();
document.getElementById("loginBtn").onclick = function () {
var maskLayer = createMaskLayer(); var loginLayer = createLoginLayer(); loginLayer.style.display = "block"; maskLayer.style.display = "block"; }; </script> </body>
</html>
|
修改为通用单例模式
职责分开:节点创建,创建单例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| function createLoginLayer() { loginLayer = document.createElement("div"); loginLayer.id = "loginLayer"; loginLayer.innerHTML = "登录窗口"; loginLayer.style.display = "none"; document.body.appendChild(loginLayer); return loginLayer; } function createMaskLayer() { maskLayer = document.createElement("div"); maskLayer.id = "maskLayer"; maskLayer.innerHTML = "登录窗口"; maskLayer.style.display = "none"; document.body.appendChild(maskLayer); return maskLayer; } function getSingleton(fn) { var instance = null; return function () { return instance || (instance = fn())//instance = fn.apply(null,arguments) }; }
var createSingletonLoginLayer = getSingleton(createLoginLayer); var createSingletonMaskLayer = getSingleton(createMaskLayer);
document.getElementById("loginBtn").onclick = function () { var maskLayer = createSingletonMaskLayer(); var loginLayer = createSingletonLoginLayer(); loginLayer.style.display = "block"; maskLayer.style.display = "block"; };
|