单例模式是什么
一个类,只允许,有一个实例,并且能通过全局变量访问到
案例
js
// 实现Storage,使得该对象为单例,基于 localStorage 进行封装。实现方法 setItem(key,value) 和 getItem(key)。
class Storage {
static getInstance() {
if (!Storage.instance) {
Storage.instance = new Storage();
}
return Storage.instance;
}
getItem(key, value) {
return window.localStorage.getItem(key);
}
setItem(key, value) {
return window.localStorage.setItem(key, value);
}
}
let storage1 = Storage.getInstance();
let storage2 = Storage.getInstance();
storage1 === storage2 //true
如果还要求写一个全局唯一弹出窗呢
- 在父盒子中上下左右居中
- 宽高不固定,由内容撑开
- 外层有灰色蒙版,透明度为 0.5
关键点
- 借助flex 居中
- 内容如何自适应撑开
- 蒙层注意层级设置
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>
</head>
<body>
<!-- 1. 在父盒子中上下左右居中
2. 宽高不固定,由内容撑开
3. 外层有灰色蒙版,透明度为 0.5
4. 自下向上弹出(可选) -->
<!-- 弹出窗组件是要求手动创建的,不是预先写死一些dom结构,在组件内 -->
<!-- <div class="modal"></div> -->
<!-- 原生开发都忘记了函数必须加上括号了 -->
<div onclick="modalOpen()">打开</div>
<div onclick="modalClose()">关闭</div>
<!-- 所谓的蒙层就是遮罩层 z-index: 999; 忘记了-->
<style>
#modalWrapper {
background-color: gray;
opacity: 0.5;
width: 100%;
height: 100%;
z-index: 999;
position: fixed;
left: 0;
top: 0;
display: none;
justify-content: center;
align-items: center;
}
#modal {
width: fit-content;
height: fit-content;
background-color: aqua;
}
</style>
<script>
// 创建弹窗容器
const getModal = (() => {
let modalInstance = null;
return () => {
if (modalInstance) return modalInstance;
const modal = document.createElement("div");
const modalWrapper = document.createElement("div");
modalWrapper.appendChild(modal);
modalWrapper.id = "modalWrapper";
modal.id = "modal";
modal.innerHTML = "我是弹出创";
modalInstance = modalWrapper;
// 弹出创组件,为何执着于,一定要跟在body内
document.body.appendChild(modalWrapper);
return modalInstance;
};
})();
const modalOpen = () => {
let modal = getModal();
modal.style.display = "flex";
};
const modalClose = () => {
let modal = getModal();
modal.style.display = "none";
};
</script>
</body>
</html>