单例模式
定义:保证一个类仅有一个实例,并提供一个访问他的全局访问点。
简而言之:一个构造函数一生只能有一个实例,不管new多少次都是一个实例。
一般应用于 : 自定义弹出层
核心代码
// 如果直接new的话,new出来的两个对象是不一样的。所以需要封装一下
// 核心代码
let instance = null;
function single(instance){
// 第一次调用的时候才会个instance赋值,之后就不会再new Person了。直接返回
if(instance == null){
instance = new Person();
}
return instance;
}
写成闭包的形式把instance
和funtion Person(){}
保存起来
let Person = (function (){
function Person (name, age, sex){
this.name = name;
this.age = age;
this.sex = sex;
}
let instance = null;
return function (...arg){
if(instance == null){instance = new Person(...arg)};
return instance;
}
})();
// 使用
// 这里不管new多少次都是一个,后面传参数没有用。
// 这里有没有new都可以。
const p1 = new Person("jack", 18, "男");
const p2 = new Person("jafadck", 188, "女");
实践应用
// 先创建一个类, 初始化
const Tip = (function () {
class Tip {
constructor() {
this.el = document.createElement("div");
this.el.className = "app";
this.callback = function () {};
this.bindEvent();
document.body.appendChild(this.el);
}
// 这里使用原生创建dom的更好。偷懒了。。。
setContent(txt) {
this.el.innerHTML = `
<div class="top">
<span class="top-delete">X</span>
</div>
<div class="content">
<span>${txt}</span>
</div>
<div class="btns">
<button class="ok">确定</button>
<button class="delete">取消</button>
</div>`;
this.el.style.display = "block";
}
// 可以进行扩展,想设置背景颜色一样。
// 设置背景颜色
setTopBg (color){
this.el.querySelector(".top").style.backgroundColor = color;
}
// 绑定事件
bindEvent() {
this.el.addEventListener("click", e => {
e = e || window.event;
const target = e.target || e.srcElement;
if (target.className === "top-delete") {
this.el.style.display = "none";
this.callback(false);
}
if (target.className === "delete") {
this.el.style.display = "none";
}
if (target.className === "ok") {
console.log("OK");
this.callback(true);
}
})
}
}
// 核心代码。
let instance = null;
return function (options = {}, cb) {
if (instance == null) {
instance = new Tip();
// 这里也可以把txt写成一个options,把传进来的参数进行使用就可以了。
instance.setContent(options.txt);
instance.setTopBg(options.topBg);
// 如果需要使用回调函数的话,再给实例创建一个callback属性,给他赋值就可以了。
// 避免你没有传cb
instance.callback = cb || function (){};
}
return instance;
}
})();
const tip = new Tip({
txt : "hello world",
topBg : "blue"
}, function (res) {
console.log("执行了", res);
});
css就放在底部了,不重点
.app {
border: 1px solid black;
width: 300px;
height: 300px;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
.app>.top {
width: 100%;
height: 30px;
background-color: skyblue;
}
.app>.top>.top-delete {
float: right;
width: 20px;
height: 30px;
border-radius: 50%;
line-height: 30px;
margin-right: 5px;
font-size: 14px;
}
.app>.content {
height: 230px;
width: calc(100% - 40px);
position: relative;
}
.app>.btns {
width: 100%;
height: 30px;
/* border: 1px solid black; */
}
.btns>.ok,
.btns>.delete {
float: right;
}
.content span {
position: absolute;
top: 50%;
text-align: center;
width: 100%;
}