js——单例模式
确保一个类仅有一个实例。
如弹窗效果,多次点击按钮也只弹出一个弹窗,程序会判断当前是否有弹窗,如果有则不弹,没有则弹;
还有防抖效果,如果当前有定时器在执行,那么就不重新启用新的定时器,只有没有定时器了再打开一个新的定时器。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.window {
width: 200px;
height: 200px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<button onclick="popupWindow('弹窗内容')">打开弹窗</button>
<button onclick="closeWindow()">关闭弹窗</button>
<script>
let createWindow = (function () {
let onlyWindow = null;
return function () {
if(!onlyWindow) {
onlyWindow = new windowObj();
}
return onlyWindow;
}
})();
function windowObj() {
let div = document.createElement('div');
div.className = 'window';
div.style.display = 'none';
document.body.appendChild(div);
return div;
}
{
let ppWindow = createWindow();
function popupWindow (msg) {
ppWindow.innerText = msg;
ppWindow.style.display = 'block';
}
function closeWindow () {
ppWindow.style.display = 'none';
}
}
</script>
</body>
</html>