- 保证一个类仅有一个实例,并提供一个访问它的全局访问点。
- 主要解决一个全局使用的类频繁的创建和销毁,占用内存。
var Singleton = function () {
var instance;
function User(name, age) {
this.name = name;
this.age = age;
}
return function (name, age) {
if (!instance) {
instance = new User(name, age);
}
return instance;
};
};
class Singleton {
constructor(name, age) {
if (!Singleton.instance) {
this.name = name;
this.age = age;
Singleton.instance = instance;
}
return Singleton.instance;
}
}
<!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>
.kerwin-modal {
position: fixed;
width: 200px;
height: 200px;
line-height: 200px;
text-align: center;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background-color: yellow;
}
</style>
</head>
<body>
<button id="open">打开</button>
<button id="close">关闭</button>
<script>
const Modal = (function () {
const instance = null;
if (!instance) {
instance = document.createElement("div");
instance.innerHTML = "登陆对话框";
instance.className = "kerwin-modal";
instance.style.display = "none";
document.body.appendChild(instance);
}
return instance;
})();
document.querySelector("#open").onclick = () => {
const modal = Modal();
modal.style.display = "block";
};
document.querySelector("#close").onclick = () => {
const modal = Modal();
modal.style.display = "none";
};
</script>
</body>
</html>